Sign in to follow this  
johnnyBravo

c++ Strange deleting pointer problem, involving inheritance.

Recommended Posts

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[i]; //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

Share this post


Link to post
Share on other sites
You have an array bounds overrun somewhere, overwriting vital information the system needs to properly deallocate the memory blocks.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
It allows you to call destructor through a pointer to the base type, which is what you were trying to do.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this