Possible Duplicate:
Why do I see strange values when I print uninitialized variables?
Fun with uninitialized variables and compiler (GCC)
I want to know about a mysterious problem which I faced while solving a code issue.
The code which is present in production has an uninitialized boolean variable and a library is checking the value of this boolean.
In LIVE site, this variable is behaving as TRUE always
The same code in development environment is behaving as FALSE always.
I know, due to the environment difference between LIVE & DEV, an uninitialized bool variable can have an undefined value.
But here is my issue.
If I put a log statement in the code, compile it and put the binary in development environment, the bool variable is having TRUE always, whereas it was FALSE with the code in LIVE.
How does a log statement affect the value of an uninitialized bool variable?
I would like to know the possibilities.
An uninitialiazed variable is just a piece of raw memory and will show as value whatever happes to be there. You idea that “In the live system it always happens to be true” is totally wrong. All you can say is that every time you observed it in the live system it seemed to be true. May be on next Tuesday instead it will happen to be false because it’s well known that uninitialized bools hate tuesdays.
Note that’s even entirely possible that an uninitialized boolean may seem true for one function and false for another (normally a full byte is allocated for a bool, but only a bit is needed to represent the value: it’s possible that an uninitialized bool will contain a magic fuzzy bool value that it’s true for someone and false for someone else).
As for what the standard says accessing an uninitialized variable for reading may indeed be undefined behavior, with no limits on what may happen including crashes (and for example is easy to have a program to “stop” when reading an uninitialized variable, just compile with a specific tool for tracking this kind of problem). Always having a program crash on accessing an uninitialized variable would be wonderful, but unfortunately it’s quite costly on current CPUs and it’s not going to happen unless specific tools are used.
Of course adding even just a
printfcall can change the apparent behavior of code handling uninitialized variables. This kind of bug is often referred to as “heisenbug” and actually the random or heisenbug behavior is often an indication of an uninitialized variable or of a thread synchronization problem.