Identical memory address for subsequent function calls

This question is closely related to this: Why is the address of a local variable identical for different executions? ... I understand the answer to this question, but if I add something to the stack between the fun calls, 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 the variable address reported by the second call to fun to be larger with 4 bytes than the previous one, since I pushed the variable p onto the stack.

My intuition is that this is some 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 that is reserved, but not highlighted) for local variables at the beginning of the function.

+3


source to share


1 answer


Because the call to the stack frame is the same. The variable p

was allocated on the stack, even before the first call was made fun

. In addition, compiler optimization plays a role. You shouldn't rely on such statistics (they are rarely useful).



+6


source







All Articles