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 this:

  • Is this certain behavior or is it just something wrong that my machine is doing?

  • If this is not some buggy thing my computer did, can you explain why the compiler wants to store loo

    at the same address asbaba?

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

I understand that the value of loo is the result of the remaining bits of baba, and I understand that (at least on my machine) the stacks of both are laid out in such a way that the loo overlaps in old baba territory. Is it true that each machine would lay these two functional stacks so that Baba and Luo overlap? Using these two functions exactly as written, that is ...

+3


source to share


1 answer


B f2()

is lolo

uninitialized. So this content is undefined .

Most often, however, the content is the data that was on the stack. Coincidentally, you first called func1()

which has exactly the same memory / stack layout as f2()

. So the random variable contains data that was previously stored in the same location.



This behavior is not guaranteed at all. It only works in that particular 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 is a small picture explaining the situation in this particular case: enter image description here

+10


source







All Articles