Bizzare optimization problem

I have a C program that, for the life of me, I can't see any possible stack corruption in but for some reason corrupts a local variable to 0 when not referenced. My compiler is gcc 4.3.4.

But my question's not really a code question, it's a compiler question. The glitch is weirdly specific: it happens at -O2 and higher. It does not happen when I individually and laboriously enable every possible -O1 and -O2 option(as reported by gcc -c -Q -O0 --help=optimizers , etc.) -- only the actual -O2 flag will cause it. What might gcc be doing in -O2 that it doesn't do when I enable every possible -O2 option?

While this does sound wierd I tend to believe that the program is at fault rather than the compiler. One thing that might help would be to compile it with a C++ compiler. I actually do this with most of my C programs. C++ is almost a superset of C and the few things I give up are things I don't miss. C++ often detects errors in my code that C has missed. Also, rather than trimming compiler options, try to reduce the program to the smallest possible amount of code that still has the bug.

I seem to recall also coming across that issue in that particular version of GCC. What happens if you compile your program with GCC 4.4 or later?

That's the problem; so much as sneezing on this code causes this bug to not happen, and yet, I can't for the life of me see that I'm doing anything wrong. I've accounted for every single step along the way -- not difficult, as it happens extremely early in the program, in a completely innocuous place that uses no stack pointers at all. I've dug down and ferreted out stranger bugs before but this time, not even a gdb memory watch could determine when fd was being modified when it goes haywire -- it just said 'optimized out'... Like it suddenly decides to stop using the variable and just assume it's zero.

It works fine in gcc 4.4.4 with -O2 and -O3, so I suspect it really is that strange and wild thing, a compiler bug. Thanks for the suggestion fpmurphy. I'd better rebuild my system.