compiling the following code with -O2, the program will core dump. I check the assembly code output, it seems the 'strlen' function call is replaced by the 'builtin strlen' funciton and will read the first four byte on a invalid memory page. And if i replace the mmap with malloc and run under the Valgrind[3.5.0],the Valgrind also reports 'Invalid read of size 4'.
Ps:How to workaround this piece of code???I think there are two ways a.mmap 4 bytes or more to make sure the strlen will not read the invalid memory b.use the gcc option '-fno-builtin-strlen' to make sure the 'strlen' is not replaced. But I'm not sure is there a more elegant way to workaroud this?? ==================================================================== #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef struct _x_t { int offset; //'strlen' is replaced iff. this field exists. char data[0]; }x_t; int main() { //make a 4K memory page. char *buff=mmap(NULL,4096,PROT_WRITE | PROT_READ ,MAP_PRIVATE | MAP_ANONYMOUS,0,0); char *buffer = buff+4096-11; strcpy(buffer,"0123456789"); x_t *x=(x_t*)buffer; printf("%d\n",strlen(x->data)); //read a invalid page. munmap(buff,4096); return 0; } -- Summary: option -O2 generates wrong assembly code Product: gcc Version: 4.4.0 Status: UNCONFIRMED Severity: critical Priority: P3 Component: c AssignedTo: unassigned at gcc dot gnu dot org ReportedBy: dirtysalt1987 at gmail dot com GCC build triplet: GNU/linux 2.6.9 Intel Xeon GCC host triplet: GNU/linux 2.6.9 Intel Xeon GCC target triplet: GNU/linux 2.6.9 Intel Xeon http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43774