請幫我我哪裏出錯了,下面是我的代碼,在刪除或釋放x之前它工作正常,但刪除x之後它顯示出我已經傾倒了。我不知道爲什麼。我所做的是,我在堆中使用new關鍵字分配了2個變量,然後p = x這意味着p現在保存了x的地址。然後我釋放了p,最後我釋放了x。請幫我解決我錯誤的地方。指針動態分配(核心轉儲)
#include <iostream>
using namespace std;
int main(){
int a;
int *b=&a;
cout<<b<<endl;//address of a
int *x=new int;
cout<<x<<endl;
cout<<*x<<endl;
int *p=new int;
*x=10;
*p=12;
p=x;
cout<<p<<endl;
cout<<x<<endl;
cout<<*p<<endl;
cout<<*x<<endl;
*x=13;
cout<<*p<<endl;
delete p;
*x=14;
cout<<*x<<endl;
cout<<*p<<endl;
delete x;
return 0;
}
那麼爲什麼刪除p後,* x = 14和cout << * x工作正常?它被刪除刪除p ....? – user3215228
@ user3215228未定義的行爲未定義。任何事情都可能發生。 –
@ user3215228查看我更新的帖子。 –