Search code examples
c++variablesprogram-entry-point

Why local int variables inside `main` function will be initialized automatically?


I'm new to C++ and have that problem while learning C++.

Here is the code

#include <iostream>
using namespace std;

void another_func() {
    int a;
    cout << a << endl;
}

int main() {
    int a;
    cout << a << endl;
    another_func();
}

I'm using g++ (GCC) 10.1.0 and I found that everytime when I run the code, the a inside the main function would be initialize to 0, while a in another_func would be a random number. As follows,

➤  g++ test.cpp && ./a.out
a in main: 0
a in another_func: 32612

As I know, local variables are storaged in the stack and they don't have auto-initialization mechanism. So the a in another_func is expected. However, can someone tell me why the a in main function was initialized to 0?

Thanks in advance!


Solution

  • Uninitialised doesn't mean non-zero, it could have any value. On many OSs freshly allocated memory pages are filled with 0 so in non-debug code uninitialised values are often 0 too.

    The behaviour of your program is undefined but what is likely happening is that a in main is either the first use of the stack or you just get lucky and the initialisation code that runs before main leaves that area of the stack 0.

    The call to cout will write to the stack so when you then execute another_func the stack memory wont be all 0 anymore.