When using the -O3 optimizing option (-O2 and -O1 as well), a sprintf call, in which the target string and the source string are the same, will no longer show the same behavior. Not sure, whether this is actually a Bug. Here is an example:
test.c: #include <stdlib.h> #include <stdio.h> char mystring[30]; int main(int argc, char *argv[]){ sprintf(mystring,"hello"); printf("%s\n",mystring); sprintf(mystring,"%s world",mystring); printf("%s\n",mystring); return 0; } terminal: m...@here ~ $ gcc -o test test.c m...@here ~ $ ./test hello hello world m...@here ~ $ gcc -O3 -o test test.c m...@here ~ $ ./test hello world m...@here ~ $ gcc --version gcc (Gentoo 4.3.4 p1.0, pie-10.1.5) 4.3.4 I'm fully aware that the line sprintf(mystring,"%s world",mystring); is kind of dangerous, as it will fail as soon as %s is not the first object inside the string or mystring has reached full length, and should be replaced with a call to strcat or similar. However, under normal conditions it will work fine, and it's quite intuitive that the optimizing option changes this behavior. Might be related to http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40479 -- Summary: O3 option changes sprintf behavior Product: gcc Version: 4.3.4 Status: UNCONFIRMED Severity: minor Priority: P3 Component: c AssignedTo: unassigned at gcc dot gnu dot org ReportedBy: schoth at itp dot physik dot tu-berlin dot de http://gcc.gnu.org/bugzilla/show_bug.cgi?id=42173