Am Freitag, den 13.06.2008, 08:08 +0200 schrieb Pavel Troller:
and when I compiled it without optimalization and with -g for debugging, it never crashed and worked perfectly under the debugger. I had to debug the optimized version, which is harder, because the generated code doesn't track the source exactly anymore. With regards, Pavel Troller
Is that a GCC bug then? And, more importantly, was that with a recent GCC version?
Hi! It cannot be clearly said. Some nuances of the C language are "implementation dependent" and it's perfectly OK to compile them differently with or without optimization. Sometimes the programmer incorrectly relies on such a nuance and then using the different set of options can cause his program to behave incorrectly.
Even more probable than encountering "implementation defined" behavior is encountering "undefined" behavior. In that case, the same program compiled with the same options might crash one day and not the other. A typical case of undefined behavior is using an uninitialized pointer. Due to address space randomization it could happen that the value in the uninitialized pointer sometimes points to valid memory and sometimes faults.
In the case of optimization dependent behavior, the most common source is a buffer overflow on a local (stack-contained) array. gcc -O0 puts all declared variables onto the stack, in the order they were declared. gcc -O2 sometimes elides variables completely or reuses the same space for different variables, so you get a totally different stack layout. This means you are overwriting different data depending on optimization, and the chance to hit a location that is currently not in use is higher without optimization. This is of course not a gcc bug. The program always does a forbidden access out of array bounds, you just don't notice without optimization, or put in other words: Without optimization the program is as wrong as with optimization, it just happens to do the right thing anyways.
Regards, Michael Karcher