Cpp代码:
#include <iostream>
using namespace std;
int* scopeProblem()
{
int *bret;
int b=10;
bret =&b;
return bret;
}
int main()
{
cout<<*(scopeProblem());
return 0;
}
输出为 10
我原以为它会出错,因为它是在函数中本地创建的变量地址。 函数执行完成后不应该存在。
正如评论者所提到的,使用超出范围的局部变量的地址会产生未定义的行为,即任何事情都可能发生,包括程序运行纯属偶然。所以,简短的回答是不要那样做。
不过,如果您好奇的话,这就是(至少在我的环境中)程序仍然设法输出
10
的方式。程序集显示,当指针被取消引用时,它仍然指向 scopeProblem
函数的堆栈帧,自调用以来未修改,因此它仍然恰好包含 10
.
考虑到这一点,您可能会弄清楚为什么以下代码打印出
2
(至少在我的平台和编译器上)。对 foo
的干预调用导致分配一个新的堆栈帧,该堆栈帧将覆盖对 scopeProblem
. 的调用的堆栈帧
#include <cassert>
#include <iostream>
int* scopeProblem()
{
int *bret;
int b=10;
bret =&b;
return bret;
}
auto foo() {
int a = 0, b = 1, c = 2;
return a + b + c;
}
int main(int argc, const char *argv[]) {
auto ptr = scopeProblem();
auto a = foo();
std::cout << *ptr << std::endl;
assert(a == 3);
return 0;
}