Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

c++ - Why is the address of a local variable identical 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 is

0xbfb8e610 
0xbfb8e610

Here loc is a local variable, which goes out of scope after the 1st execution of the function f(10), then get allocated again for the next execution of fun(11). So the address of loc variable has to be different as per my understanding. Then why is the address &loc same for both the execution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Each invocation of fun needs its own place to store the variable. But as soon as the function returns, the variable no longer exists. There's no reason the address can't be re-used. It doesn't have to be, but there's no reason it can't be.

In a typical implementation, stack space is used to hold the information needed to return from a function and their local variables when a function is invoked. When the function returns, the local variables are removed from the stack and the return information popped off it, leaving the stack back where it was when the function was called. Since the two function invocations are the same, they wind up with the stack the same in both cases, making the local variable have the same address. This is what an experienced programmer would would expect, but not rely on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...