0

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

Returning the address of a variable inside a function is bad because that variable will no longer exist if the stack frame where the variable belongs end.

So why this code works fine

int* test(){
    int a = 11;
    return &a;
}

int main(){

    int *a;
    a = test();

    cout << *a;

    return 0;

}
4

2 回答 2

5

那么为什么这段代码可以正常工作

未定义的行为意味着代码看起来可以正常工作。但它仍然是未定义的。

在您的情况下,a是一个悬空指针。

于 2012-08-08T18:07:14.970 回答
0

代码仍然是错误的。它现在可能看起来有效,但下周不会。它现在似乎可以工作,但改变一件小事,它就不再“工作”了。

尝试这个。添加另一个功能,test2

int *test()
{
    int a = 11;
    return &a;
}

int test2()
{
    int b = 13;
}

int main()
{
    int *a;

    a = test();
    cout << "after test: " << *a << endl;

    test2();
    cout << "after test2: " << *a << endl;

    return 0;
}

现在是11两次打印?请注意,它仍然可以打印11两次,但可能不会。毕竟,我们仍然在这里与未定义的行为调情。

但在我的机器上,我看到:

after test: 11
after test2: 13

test2已经破坏了我的悬空指针指向的堆栈空间。代码不正确。函数内部定义的变量在test函数退出时超出范围,不再有效。保持对它的引用不会改变这一点。

于 2012-08-08T18:08:16.420 回答