开发者

What happened to local pointer? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

My questions are marked in code comments in the snippet below.

int *foo(){
    int a = 10;
    int b = 20;
    return &b;
}
int *foo2(){
    int aa = 44;
    int bb = 40;
    return &bb;
}

int main(int argc, char* argv[])
{
    int *p = foo();
    int *p2 = foo2();

    int  a = 700;
    int *b = & a;

//  cout<<开发者_StackOverflow社区;*b<<endl; /* what & why the difference from adding & removing this line?? */
    cout<<a<<endl;
    cout<<*p<<endl; /* what & why happened to "p" */

    return 0;
}


In foo() and foo2() you are returning pointers to local variables. These locals have automatic storage and it is undefined behavior to use a pointer to them once they go out of scope. Therefor p and p2 contain nothing useful. It might work, it might not.

I can't understand your question very well, so I hope I got it all.


Before I attempt to answer the questions in the comments of your code snippet, let's step through this:

int *foo(){
    int a = 10;
    int b = 20;
    return &b;
}
int *foo2(){
    int aa = 44;
    int bb = 40;
    return &bb;
}

int main(int argc, char* argv[])
{
    int *p = foo();
    int *p2 = foo2();

In both foo() and foo2(), you're returning a pointer to something located in the function call stack (that is, a, b, aa, and bb), which will go away when the function returns. Within the function a pointer to variables a or b in foo() or a pointer to variables aa or bb in foo2() will point to something valid.

But when the function returns, those variables will cease to exist. So in both of these functions the returned pointer will not be valid, and consequently p and p2 will be invalid as well.

    int  a = 700;
    int *b = &a;

You're assigning the address of the variable a to pointer b.

//  cout<<*b<<endl; /* what & why the difference from adding & removing this line?? */

Adding the line will dereference b and print out the value of the pointee (in this case, the value of variable a which is 700).

    cout<<*p<<endl; /* what & why happened to "p" */

Since p is invalid as explained earlier, it will invoke undefined behavior, meaning anything can happen. That can include it working just fine (which I doubt), printing garbage values, crash outright, or explode your computer. Just don't try to dereference an invalid pointer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜