删除指针时程序崩溃

Program crashes when deleting a pointer

本文关键字:崩溃 程序 指针 删除      更新时间:2023-10-16

大家好 我的代码是:

class aClass
{
public:
    int data;
    aClass* pointer=NULL;
    aClass(int x): data(x) {
        cout << "calling int constructorn";
    }
    ~aClass() {
        delete pointer;
        cout <<"Index " <<this->data<<" calling destructorn";
    }
};
int main()
{
    aClass ob1(1);
    ob1.pointer=new aClass(2); // let's say the new object is called ob2
    ob1.pointer->pointer=new aClass(3);// let's say the new object is called ob3
    delete ob1.pointer; //destory ob2, which will destory ob3 in sequentially.
    return 0;
}

我期望输出是这样的:

calling int constructor
calling int constructor
calling int constructor
Index 2 calling destructor
Index 3 calling destructor //I think when ob2is destoyed ob3 will be destoyed 
                           //too, but this is not in the output even though I delete "delete pointer" in 
                           //the destructor           
Index 1 calling destructor
但是程序崩溃

了,我知道它在析构函数中的"删除指针"使程序崩溃,但我不知道它为什么崩溃以及为什么 ob3 没有被解救?

当退出 main 时,ob1 会自动销毁,因此调用其析构函数。再次删除pointer,从而导致崩溃。请勿手动删除ob1.pointer

这是一个基本示例,可帮助您了解正在发生的事情。

class C
{
public:
    C* p;
    C() : p(NULL)
    {}
    ~C()
    { delete p; }
};
int main()
{
    C a;
    // ...
    // Lets say a.p == 5 for some reason.
    delete a.p;
    // The memory at address 5 is now deleted, but a.p remains unchanged.
    // a.p is still 5, but accessing it is now illegal.
    return 0;
    // Stack cleanup -> a is destroyed.
    // a´s destructor is called, which attempts to delete its p.
    // This p is a.p which was deleted earlier.
    // Remember, a.p is still 5, and now it is deleted in ~C.
    // -> You deleted the memory at address 5 twice.
}