C++ program crashes

Hi,

Could anyone tell me the reason why the following program crashes?

class A {
    int x;
public:
    A() {
        cout << "from A()" << endl;
    }

    ~A() {
        cout << "from ~A()" << endl;
    }
};

class B : public A {
public:
    B() {
        cout << "from B()" << endl;
    }

    virtual ~B() {
        cout << "from ~B()" << endl;
    }
};

int main() {
    A* a = new B;
    delete a;
}

when I drilled down the core-dump, I got *** glibc detected *** a.out: free(): invalid pointer: 0x0804a00c ***

I know the base class destructor need to be declared "virtual". But what is the exact reason for crashing?

That's going to be implementation-specific, since it depends on how your compilers' virtual tables work. bottom line, freeing the wrong pointers because you're freeing the wrong type.

I got a reply in another forum as below which I would like to share here.

Sizeof(A) = 4 bytes
Sizeof(B) = 8 bytes

When you assign an instance of derived class object to its base class pointer, then the base class pointer points to the base part of the derived class object.
On freeing, it tries to free 8 bytes but only 4 bytes allocated for base part.

If you want to delete the object, delete a object with a pointer to its actual type as

B* b = new B;
A* a = b; // you can use the object via either b or a but
delete b; // delete as b
b = null;