我可以知道为什么下面的代码没有出错,即使函数返回局部变量的地址

问题描述 投票:0回答:1

Cpp代码:

#include <iostream>
using namespace std;

int* scopeProblem()
{
    int *bret;
    int b=10;
    bret =&b;
    
    return bret;
}

int main()
{
    cout<<*(scopeProblem());
    return 0;
}

输出为 10

我原以为它会出错,因为它是在函数中本地创建的变量地址。 函数执行完成后不应该存在。

c++ variables scope local
1个回答
0
投票

正如评论者所提到的,使用超出范围的局部变量的地址会产生未定义的行为,即任何事情都可能发生,包括程序运行纯属偶然。所以,简短的回答是不要那样做。

不过,如果您好奇的话,这就是(至少在我的环境中)程序仍然设法输出

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.