Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an invalid block crash when deleting objects involved in multiple (virtual) inheritance?

I'm editing this question to make it more readable and less contrived. I've managed to replicate my issue with the following short piece of code. The question, then, is: why does this crash on an assertion failure with _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) on the "delete p" line in ~A()?

class A;

class I
{
public:
    I(const A *p) : parent_(p) {}

    virtual void foo() = 0;
protected:
    const A *parent_;
};

class I1 : public virtual I
{
public:
    I1(const A *p) : I(p) {}

    virtual void foo() {}
};

class A
{
public:
    A() {}
    virtual ~A()
    {
        for (size_t i = 0; i < it_.size(); ++i)
        {
            I *p = it_.at(i);
            delete p;
        }
    }

    virtual I* add() { I *p = new I1(this); it_.push_back(p); return p; }
protected:
    vector<I*> it_;
};


int _tmain(int argc, _TCHAR* argv[])
{
    A *a = new A();
    for (int i = 0; i < 10; ++i) a->add();
    delete a;

    system("pause");
    return 0;
}
like image 339
neuviemeporte Avatar asked Dec 12 '25 22:12

neuviemeporte


1 Answers

Is the destructor of SeqItem virtual? If not, you have undefined behavior; in practice, this undefined behavior will only display immediate disasterous results if multiple inheritance is involved, and even then, not necessarily unless the inheritance is virtual. (Without multiple inheritance, it will typically seem to work, although it will often leak memory.)

like image 77
James Kanze Avatar answered Dec 14 '25 11:12

James Kanze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!