c++ - g++ 悬挂指针警告不一致?

标签 c++ pointers g++ compiler-warnings

这是同一件事吗?

1.

int* f() {
    int x = 5;
    return &x;
}

2.

int* f() {
    int x = 5;
    int* pX = &x;
    return pX;
}

g++ 只返回 1. 的警告,为什么不返回 2.?

最佳答案

Is this the same thing?

是的。

g++ only returns a warning for 1., why not 2.?

我不确定,但我的猜测是 return 语句是获取局部变量地址的第一步。在执行 return 语句时,编译器不一定知道 pX 是如何设置的。

int* f() {
    int x = 5;

    // There is no problem here.
    int* pX = &x;

    // The compiler doesn't care to find out how pX was set.
    // it could have been pX = malloc(sizeof(int))
    // It assumes that pX is a valid pointer to return.
    return pX;
}

关于c++ - g++ 悬挂指针警告不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33206145/

相关文章:

c++ - 如何在保持高效的同时正确使用继承?

c++ - 如何用C++模拟数字电路(只是输入/输出,没有图形)

c++ - 如果 Windows 正在关闭或重新启动,有没有办法以编程方式接收?

pointers - gcc C/C++ 假设没有指针别名

c - 如何使用指针表示法访问二维数组中的结构元素?

c++ - 从模板参数指向方法的指针

c++ - 尝试使用 g++ 为 64 位 Windows 编译 .cpp

c++ - g++ : should --std option change which STL/stdlib my code uses?

C++11 constexpr 导致编译器的内部错误 (C1001)

c++ - G++、clang++ 和 std::function