【问题标题】:g++ dangling pointer warning inconsistency?g++ 悬空指针警告不一致?
【发布时间】:2015-10-19 03:22:39
【问题描述】:

这是一样的吗?

1.

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

2.

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

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

【问题讨论】:

  • 它们略有不同,在第一个示例中,x 将在函数返回时被销毁。在第二种情况下,x 的地址已经存储在pX中,所以x的销毁不会删除pX中存储的值,你可以像一个简单的整数值一样返回。
  • @Alparslan:所以 pX 将 x 保留在堆栈中?
  • 不,它不会强制将 X 保留在堆栈中,但它只是将 X 的旧地址保存为单独的整数,即使在 X 被销毁后您也可以返回它。
  • @Alparslan:所以 2. 仍然具有与 1 相同的内存含义。?也就是有没有可能 2. 指针指向不一致的值?
  • 没错,在这两种情况下,返回的内存地址都是无效的。如果你在这两种情况下都尝试在返回的地址上写,你可能会崩溃你的程序。

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


【解决方案1】:

这是一样的吗?

是的。

g++ 只返回 1. 的警告,为什么不返回 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;
}

【讨论】:

  • @R Sahu:我不太明白你的回答。
  • @wulfgar.pro,我在答案中添加了更多内容。
  • 我明白了,所以 1. 的相同含义仍然存在于 2. 中,只是 g++ 没有捕捉到这种情况?
【解决方案2】:

我可以通过开启优化see it live 来让 gcc 对这两者发出警告:

warning: address of local variable 'x' returned [-Wreturn-local-addr]
 int x = 5;
     ^

 warning: function returns address of local variable [-Wreturn-local-addr]
 return pX;
        ^

这些类型的警告通常会受到优化级别的影响,gcc has a ten year old bug report on the inconsistency of the detecting use of a variable before initialization 根据优化级别的不同而有很大差异。

最终,当您有未定义的行为时,编译器没有义务提供诊断,事实上,由于difficulty of consistently detecting them,许多行为被指定为未定义而不是格式错误。

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多