Why are local variables initialized to 0 in the g ++ compiler for c ++ in ubuntu linux?


As per any book on c++, any local variable of c++ which is not initialized will contain a garbage value. However, check out this following program:

using namespace std;
float a;
class A
float b;
int main()
float c;
static float d;
static float e = 0;
A f;
cout<<"\n global a : "<<a<<"\n class variable b : "<<f.b;
cout<<"\n local c : "<<c<<"\n static local d : "<<d
<<"\n static initialized local e : "<<e;

If compiled with g++ on ubuntu linux it gives the following output:

global a : 0
class variable b : 6.94896e-36
local c : 0
static local d : 0
static initialized local e : 0

The strange thing is that it gives a 0 value for the local variable c, whereas this should be uninitialized and contain some garbage value. The same program works differently with visual c++ for windows and gives a garbage value for c which is what you would expect.

The local variable c is left uninitialized. This means, as you say, that it has a garbage value. The object may have any value, including 0. Zero is valid "garbage value." In general, you are not allowed to read from an object that has not been initialized.

Why is the value of c zero? It could be that the compiler (g++) is zero-initializing the stack when the function is entered, to "help" your program to perform "correctly" even if it makes use of uninitialized variables. Or, it could be that the operating system is zero-initializing pages of memory before it gives them to your program. Or, perhaps a function that was called before main stored the value zero in the byte array now occupied by c, so it has a zero value.

The behavior of a binary compiled with Visual C++ depends on how it is compiled. In a release binary, where performance is more important than debuggability, the stack is not implicitly initialized when a function is entered, so c will be left uninitialized and will have a garbage value.

In a debug binary, where debuggability is more important, all local variables are initialized with the byte 0xcc. This can help you to track down and debug usage of uninitialized variables. Similarly, the debug heap initializes newly allocated storage with the byte 0xcd, and it fills memory with different bit patterns as it is allocated and deallocated, to help you to debug the state of the program.