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

g++ dangling pointer warning inconsistency?

这是同一件事吗?

1.

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

2.

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

g++ 仅 returns 对 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;
}

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

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,许多行为被指定为未定义的而不是格式错误的.