Search code examples
c++diamond-problem

C++ heap error _CrtlsValidHeapPointer(pUserData)


After I compile with MSVC, my program triggers an assertion failure at runtime: _CrtlsValidHeapPointer(pUserData) , but the code looks ok to me...

class A
{
    int a;
public:
    A();
    A(int);
    virtual ~A();
    void setA(int);
    int getA();
    virtual void function()=0;
};

class B : virtual public A
{
    int b;
public:
    B();
    B(int,int);
    void setB(int);
    int getB();
    void function();
};

class C : virtual public A
{
    int c;
public:
    C();
    C(int,int);
    void setC(int);
    int getC();
    void function();
};

class D :public B,public C
{
    int d;
public:
    D();
    D(int,int,int,int);
    void setD(int);
    int getD();
    void function();
};

int _tmain(int argc, _TCHAR* argv[])
{
    A **p = new A*[4];
    int i;
    for(i=0;i<4;i++)
    {
        p[i]=new D(4,3,12,1);
    }
    for(i=0;i<4;i++)
    {
        p[i]->function();
    }
    for(i=0;i<4;i++)
    {
        delete p[i]; //the assertion fails when attempting to delete p[1]
    }
    delete[] p;
    system("pause");
    return 0;
}

What's wrong with my code?


Solution

  • You need a virtual destructor in A. It doesn't have to do anything here, but it must be declared as virtual.

    In general, if you delete an object of a derived type through a pointer to a base type, the base type must have a virtual destructor.