这是同一件事吗?
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/