Why is the local variable address the same for different executions?

int fun(int x);

int main()
{
    fun(10);
    fun(11);   
    return 0;
}

int fun(int x)
{
    int loc;//local variable
    cout<<&loc;
    return 0;
}

      

Output

0xbfb8e610 
0xbfb8e610

      

Here loc is a local variable going out of scope after the first execution of the function f(10)

, and then re-allocated for the next execution fun(11)

. Therefore, the address of the variable loc

should be different according to my understanding. Then why is the address &loc

the same as for execution?

+1


source to share


3 answers


Each call fun

needs its own place to store the variable. But as soon as the function returns, the variable no longer exists. There is no reason the address cannot be reused. It is not necessary, but there is no reason why it cannot be.



In a typical implementation, stack space is used to store the information needed to return from the function and their local variables when the function is called. When the function returns, the local variables are popped off the stack, and the returned information is popped out of it, leaving the stack back where it was when the function was called. Since the two function calls are the same, in both cases they are the same on the stack, making the local variable the same address. This is what an experienced programmer expected, but did not rely on.

+7


source


A somewhat ultra-simplified (vague) illustration of what happens on the stack.

main()

(assuming it 0xtopomain

remains constant):

   ~Stack~
==============
= 0xtopomain =
= 0x........ =
==============

      

First execution fun()

(push):

   ~Stack~
==============
= 0xothers.. =
= 0xbfb8e610 = <- loc
= 0xmemoffun = <- other memory allocated for fun()
= 0xtopomain =
= 0x........ =
==============

      



Back to main()

(pop):

   ~Stack~
==============
= 0xtopomain = <- Where the hell is loc?!!
= 0x........ =
==============

      

Second run fun()

(click again):

   ~Stack~
==============
= 0xothers.. =
= 0xbfb8e610 = <- loc here again
= 0xmemoffun = <- other memory allocated for fun()
= 0xtopomain =
= 0x........ =
==============

      

+3


source


Local variables stored on the stack (a special area of ​​memory in which newly pressed variables remain at the top and old variables remain at the bottom). When you make a function call, some operations are performed like the store return address, parameters and registers, etc. But there is an order. And in response time, all pushed variables popped off the stack. Since you are using the same function and between two calls, you are not using a local variable in the main function, your address variables are expected to be the same.

+2


source







All Articles