可能重复:
Can a local variable's memory be accessed outside its scope?
在函数内返回变量的地址是不好的,因为该变量将不再存在 如果变量所属的堆栈帧结束。
为什么这段代码工作正常
int* test(){
int a = 11;
return &a;
}
int main(){
int *a;
a = test();
cout << *a;
return 0;
}
答案 0 :(得分:5)
为什么这段代码工作正常
未定义的行为意味着代码可以出现以正常工作。但它仍未定义。
在您的情况下,a
是一个悬空指针。
答案 1 :(得分: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
中定义的变量超出范围,并且不再有效。保持对它的引用不会改变这一点。