gpt4 book ai didi

c++ - 作用域结束后重新分配

转载 作者:行者123 更新时间:2023-11-30 02:59:19 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
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 undefined behavior seems appropriate..你能再验证一下吗?我试图在以下代码中模拟上述内容,但现在它给出了 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;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com