XDnl
XDnl

Reputation: 470

Virtual method crash with MSVC

I think I found a bug in MSVC's compiler (MSVC Ultimate 2012 Version 11.0.61030.00 Update 4).

#include "stdafx.h"

class Base
{
public:
    Base()
    {
    }

    void print()
    {
        printf("Base::print()\n");
    }
};

class Derived : public Base
{
public:
    Derived() : Base()
    {
    }

    virtual void print()
    {
        printf("Derived::print()\n");
    }
};

class DerivedSquared : public Derived
{
public:
    DerivedSquared() : Derived()
    {
    }

    void print()
    {
        printf("DerivedSquared::print()\n");
    }
};

int main(int argc, char *argv[])
{
    Base *obj1 = new Base();
    Base *obj2 = new Derived();
    Base *obj3 = new DerivedSquared();

    obj1->print();
    obj2->print();
    obj3->print();

    // Memory leaks are ALWAYS nasty :P
    delete obj1;

    // CRASH!!!
    // File: f:\dd\vctools\crt_bld\self_x86\crt\src\dbgdel.cpp
    //  _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
    delete obj2;
    delete obj3;

    return 0;
}

The particularity in that code is that Base's printf() method is not virtual, while Derived's one is. This doesn't happen with GCC (I've tested that with codepad). I wonder if this is an actual compiler bug or I'm missing something obvious.

Thoughts?

Upvotes: 1

Views: 92

Answers (3)

barak manos
barak manos

Reputation: 30156

The problem occurs without calling the 'print' functions, and can be resolved by adding a virtual destructor to each class.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 311146

As for me then it looks like a bug. I mean calling the print function that ends with crash if you are speaking about this.

Upvotes: 0

Igor Tandetnik
Igor Tandetnik

Reputation: 52621

5.3.5/3 In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

Emphasis mine. Crashing is one possible manifestation of undefined behavior. "Nothing bad appears to happen" is another.

Upvotes: 4

Related Questions