c ++删除指针,然后访问它指向的值

Ser*_* Qi 0 c++ pointers

我刚学习了C++指针和删除指针.我自己尝试了这个代码

# include<iostream>

using namespace std;

int main(){
    int num = 10;
    int *p = new int;

    p = &num;
    cout << *p << endl;
    delete p;
    cout << num << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

删除指针后p,我无法打印值num.但如果我p在程序的最后删除,cout << num << endl;会给我10.任何人都知道我在哪里运行?

Cor*_*mer 11

你先泄漏一个指针

int *p = new int;
p = &num;  // You just leaked the above int
Run Code Online (Sandbox Code Playgroud)

然后非法删除你没有删除的东西 new

delete p;  // p points to num, which you did not new
Run Code Online (Sandbox Code Playgroud)

  • @CompuChip他在删除之前被取消引用 (2认同)