I have a class named “Packet” with this destruct:
class Packet
{
...
RequestPtr req;
~Packet()
{
if (req && isRequest() && !needsResponse())
delete req;
deleteData();
}
};
The RequestPtr looks like:
typedef Request* RequestPtr;
class Request
{
...
~Request() {}
}
Problem is when delete req; and consequently ~Request() {} are executed, I get this error:
*** glibc detected *** double free or corruption (fasttop): 0x0000000002a8a640 ***
At first I thought that maybe req were deleted somewhere else and when it want to execute delete req;, obviously there is no req. However as you can see, there is a if statement which checks if the req is defined or not. So definitely when it want to delete req, the object is defined.
What does this error really mean?
The default copy constructor and assignment operator are used in class
Packetand you have a pointer to dynamically allocated memory.If a copy of
Packetis made and the original object destroyed a double deallocation will occur when the second object is destroyed. Either implement the copy constructor and assignment operator or prevent copying ofPacketby declaring themprivate.The check
if (req)will be true ifreqis not NULL, not if it has already been deallocated (as stated by Mat in comment to question).If you
delete reqin some other method of the class you must setreqto NULL:Or a double deallocation will occur.
Just to note that calling
deleteon a NULL pointer has no effect, so the following is safe: