这是一回事吗?
1
int* f() {
int x = 5;
return &x;
}
2
int* f() {
int x = 5;
int* pX = &x;
return pX;
}
g ++仅返回1.的警告,为什么不返回2.?
答案 0 :(得分:3)
这是一回事吗?
是
g ++仅返回1.的警告,为什么不返回2.?
我不确定,但我的猜测是return
语句从获取局部变量的地址中删除了一步。在pX
语句执行时,编译器不必知道return
的设置方式。
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;
}
答案 1 :(得分:3)
我可以通过启用优化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,许多行为被指定为未定义而不是形成错误。< / p>