strchr bug?

Vadim Egorov
Tue Nov 9 04:37:00 GMT 1999

While porting ElectricFence to cygwin I encountered a problem
with strchr implementation in newlib.
When it finds character occurance near the end of string it seems 
to access (sometimes) memory past the end of string. When the memory
just after the end of string is unaccessible it causes access violation.
This can be reproduced by the following program:

-------------- --------------
#include <string.h>
#include <windows.h>
char pattern[] = "::\0";

int main()
    DWORD dw;
    int len = 4;
    if (sizeof(pattern) != len)
        return 1;
    char* base = (char*)VirtualAlloc(0, 0x10000, MEM_COMMIT, PAGE_READWRITE);
    char* end = base + 4096;
    if (!VirtualProtect(end, 4096, PAGE_NOACCESS, &dw))
        return 1;
    char* p = end - len;
    memcpy(p, pattern, len);
    p = strchr(p, ':');
    return 0;
-------------- --------------

What confuses is that it happens only when optimization is turned on:
gcc -O2 -o test
I tried it with gcc 2.95 and 2.95.2 and recent cygwin snapshots.
Any idea?

Vadim Egorov 

Want to unsubscribe from this list?
Send a message to

More information about the Cygwin mailing list