whoisit
whoisit

Reputation: 269

Program crashes when deleting a pointer

Hi guys My code is:

class aClass
{
public:
    int data;
    aClass* pointer=NULL;

    aClass(int x): data(x) {
        cout << "calling int constructor\n";
    }

    ~aClass() {
        delete pointer;
        cout <<"Index " <<this->data<<" calling destructor\n";
    }
};

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;
}

I was expecting the output to be like this:

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

But the program crashed, I know its "delete pointer" in the destructor that crashed the program, but I have no idea about why it crashed and why ob3 is not destoyed?

Upvotes: 0

Views: 788

Answers (1)

Beta Carotin
Beta Carotin

Reputation: 1679

When exiting main, ob1 is destroyed automatically, so its destructor is called. There pointer is deleted again, which results in the crash. Don´t delete ob1.pointer manually.

Here is a basic example to help you understand what is going on.

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.
}

Upvotes: 3

Related Questions