Thursday, October 14, 2010

Easy way to get glibc's "free(): invalid pointer" message

I agonized over this error for a while, because there was no obvious problem:

*** glibc detected *** ./test: free(): invalid pointer: 0x0921964c ***
... [memory dump]


The thing being deleted was a pointer to a base class, which came from a container. I was using base class pointers in the container so it would be polymorphic.

The error message implied that something was being deleted twice, and the stack track pointed me to the code that was cleaning up the pointers from my container. But after staring at it for some time, I determined that the pointer was NOT being deleted twice! So, what gives?

The answer was frustratingly simple:
The base class destructor was not virtual.

DUH!!!!!!!!!

This actually tricked me, because the sub-class was using the 'virtual' keyword with its destructor, which implied that the parent class destructor was virtual. But it wasn't! And the result was this whack-o error when I deleted the object.

No comments: