c++ Strange deleting pointer problem, involving inheritance.

Started by
6 comments, last by johnnyBravo 18 years, 7 months ago
Hi, i'm using c++ And my problem is when I try to delete some pointers it gives me the error:

//I have a pointer like so:
Layer **layers = new Layer*[3];

//I then do:
layers[0] = new InputLayer(); //These classes
layers[1] = new HiddenLayer(); //inherit from
layers[2] = new OutputLayer(); //the Layer class.

//And I delete them like so:
for(int i=0;i<3;i++) {
    delete layers; //it crashes here with the message above.
}

delete [] layers;

I can't really see what I am doing wrong here, but I guess it must be obvious to someone else. Any idea on what is causing it to crash when I delete pointers from the array? THanks
Advertisement
You have an array bounds overrun somewhere, overwriting vital information the system needs to properly deallocate the memory blocks.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Does your base class have a virtual destructor?
Quote:Original post by SiCrane
Does your base class have a virtual destructor?


No.... why? is that important?

edit... it works now, but I don't understand what putting a virtual on the destructor does?
It allows you to call destructor through a pointer to the base type, which is what you were trying to do.
Quote:Original post by SiCrane
It allows you to call destructor through a pointer to the base type, which is what you were trying to do.


To expand on this, you run into problems whenever you have a situation like this:

Base * pointer = new Derived; //calls Base() then Derived()...delete pointer; //do I call ~Base(), ~Derived(), ~Derived2()? Can't tell if the destructor isn't virtual, so assume we just call ~Base()


Making the destructor virtual avoids this problem - ~Derived() "overrides" instead of just "hides" ~Base(). It'll call the "real" ~Base() after it's completed of course.

There's talk of adding this as an automatic feature of C++ in the future. The VC debug library appears to be getting confused over mismatched ctor/dtors for reasons I certainly can't decern off the top of my head.
If I had to guess, I'd say there was multiple inheritance involved in one of those so that the base pointer being passed to the deallocation function didn't match the pointer that was returned by the allocation function, which means that the block check didn't pass.
Thanks guys, I think I understand how it works now.

Thanks alot.

This topic is closed to new replies.

Advertisement