All good C++ programmers know how to avoid leaking memory (or resources like sockets):
- Always use smart pointers, i. e.:
std::auto_ptr
,boost::shared_ptr
. - Always be aware of ownership of object: who owns, who refers, who is responsible, etc.
But, memory leaks still happen. Point most common issues when you discovered a memory leak in a program, even when you used the above techniques.
I start:
Sometimes you forget to define a destructor of base class as virtual. So all derived classes referred by pointer to the base class which was not destroyed properly and therefore leaked.
Circular references are common, and they aren't solved by
std::auto_ptr
orboost::shared_ptr
There is no substitute for (2) on your list, which is using your brain.A mistake made by people too familiar with automatic garbage collection (through smartpointers):
There are many more types of errors than just leaks. In order from worst to best:
Memory corruption.
Data is stored to an area where it shouldn't. This results in both the majority of security problems and is by far the hardest to track down.
X
is stored to an array element reserved for a base type ofX
, and the size ofX
is greater than the size of its base.new
/free
,malloc
/delete
)delete
orfree
is called twice on the same pointer.Failure to release memory
Memory no longer in use by the program remains allocated.
new[]
/delete
instead ofnew[]
/delete[]
.smart_ptr
is used in a circular data structure without attention to usingweak_ptr
for the circular link.Maybe I am out of scope, but I had some strange errors trying to "delete" uninitialized pointers.
To "avoid" memory leakage, I use the
try {} __finally {}
structure if implemented (but I read somewhere it may be inefficient if an exception was raised in a sub-sub-call)