假设我们有以下代码
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;
}
我想知道为什么会这样……应该是段错误!
好的未定义行为似乎合适..你能再次验证它吗?我试图在下面的代码中模拟上面的东西,但现在它给出了 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;
}