【发布时间】:2012-10-20 08:37:01
【问题描述】:
可能重复:
Returning the address of local or temporary variable
Can a local variable’s memory be accessed outside its scope?
假设我们有以下代码
int *p;//global pointer
void foo() {
int a=10;//created in stack
p = &a;
}//after this a should be deallocated and p should be now a dangling pointer
int main() {
foo();
cout << *p << endl;
}
我想知道为什么会这样……应该是段错误!
OK 未定义的行为似乎合适..你能再次验证它吗?我试图在下面的代码中模拟上面的东西,但现在它给出了 SIGSEGV。
int main() {
int *p=NULL;
{
int i=5;
int *q = &i;
p=q;
delete q;//simulates the deallocation if not deallocated by the destructor..so p becomes a dangling pointer
}
cout << *p << endl;
}
【问题讨论】:
-
未定义的行为意味着任何事情都可能发生,包括看起来有效。
-
也许这就是全局变量不好的原因之一
-
清理可能不会立即进行。因此,这并不意味着一旦函数执行完成,存在“a”的堆栈就会展开。这取决于执行环境,但我们唯一可以确定的是“这样做不安全”。
-
@alestanis:不,这不是全局变量不好的原因之一,因为如果指针作为返回值传递也会发生同样的情况。当然,这并不意味着全局变量就不错。这只是意味着这不是一个例子。
-
@celtschk 是的,但是那里有一个很大的警告
标签: c++ memory-management segmentation-fault lifetime