This question is closely related to this one: Why is the address of a local variable identical for different executions? . I understand the answer to that question, but if I add something on the stack between the calls to fun, the address is still the same:
int fun(int x);
int main()
{
fun(10);
int p = 0x12345678;
fun(11);
return 0;
}
int fun(int x)
{
int loc;//local variable
cout<<&loc;
return 0;
}
I expected that the variable address reported by the second call to fun to be greater with 4 bytes than the previous one, as I introduced on the stack the variable p.
My intuition says that this is a sort of compiler optimization, more specifically the memory for p is 'allocated' before it is actually defined, which goes further to the conclusion that memory is allocated (maybe I should say reserved, not allocated) for local variables at the beginning of the function.
Because the call stack frame is same. Variable p was allocated on stack, even before first call to fun was made. Other than this, compiler optimization play its role. You shouldn't rely on such statistics (they are seldom useful).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With