Search code examples
c++cmemorycompiler-constructionruntime

Memory: how does the compiler choose where to store variables?


Given two functions, func1 and f2, with the following signatures:

void func1(){
    int baba = 12345;
    // printf the value of baba here
}

void f2(){
    int loo;
    //printf the value of loo here
}

...if I run my int main, which only has func1 then f2:

int main(){
      func1();
      f2();
}

...then the printed value of both baba and loo will be 12345. So my question is as follows:

  1. Is this defined behaviour, or just something erroneous that my machine does?

  2. If this isn't some erroneous thing my computer did, can you explain why the compiler chooses to store loo in the same address as baba?

EDIT: I guess I should ask, if I have these EXACT two functions, will baba and loo have the same value on ANY machine?

I understand loo's value is the result of baba's leftover bits, and I understand that (on my machine, at least) the stacks of both are being laid out such that loo overlaps onto baba's old territory. Is it true that every machine would lay these two function stacks out in such a manner that baba and loo overlap? Using these two functions exactly as written, that is...


Solution

  • In f2(), lolo is uninitialized. It's content is hence undefined.

    Most often however, the content appears to be the data that was on the stack. By coincidence, you've first called func1(), which has exactly the same memory/stack layout than f2(). So by chance the variable contains the data that was previously stored at the same place.

    This behavior is not guaranteed at all. It only appears to work in this specific context because no other local variables were created between the two calls, and no other function call overwrites the data with other content (and the two functions have exactly the same memory layout).

    Here a small picture to explain the situation in this specific case: enter image description here