Code crashes when derived class' destructor is virtual and base class' dtor is not

I tried the following code on gcc 4.4.5.

If the member 'data' is not present, the code executes fine, but in its presence, it crashes. It also doesn't crash when the derived class' dtor is not virtual.

I'm aware that the behavior would be Undefined as listed in C++03 (5.3.5 / 3) in both the cases, but still could someone provide me with some explanation why does it crash in the latter case?

And yes, I know UB means that anything can happen, but still I'd like to know implementation-specific details.

#include<iostream>    
using std::cout;

struct base{
int data;
   base(){
      cout << "ctor of base\n";
   }
   ~base(){
      cout << "dtor of base\n";
   }
};

struct derived :  base{
   derived(){
      cout << "ctor of derived\n";
   }
   virtual ~derived(){
      cout << "dtor of derived\n";
   }
};

int main(){
   base *p = new derived;
   delete p;
}
6
задан Prasoon Saurav 27 May 2011 в 16:57
поделиться