The basic concept of memory leaking is a mismatch of a new/delete operation during code execution, either due to wrong coding practices or either in cases of errors when the delete operation is skipped.
But recently I was asked a question in an interview about other ways in which memory can leak.
I had no answer to it. What is it?
Common dynamic memory problems are:
newand not deallocating withdelete.new[]and deallocating withdelete.newand deallocate it withfree.mallocand deallocate it withdelete.In addition to memory leaks/memory corruption the last 3 scenarios will cause the dreaded Undefined Behavior.
A few other potential memory leak causing scenarios that I can recollect are:
A code example:
– Pointers in STL Containers
A more common and often encountered scenario is, Storing pointers pointing to dynamically allocated types in STL containers. It is important to note that STL containers take ownership of deleting the contained object only if it is not a pointer type.
One has to explicitly iterate through the container and delete each contained type before deleting the container itself. Not doing so causes a memory leak.
Here is an example of such an scenario.
– The Non virtual Base class destructor problem
Deleting an pointer to Base class which points to any dynamically allocated object of derived class on heap. This results in an Undefined Behavior.
An code example:
In the example only the destructor MyClass::~MyClass() gets called and MyClass2::~MyClass2() never gets called. For appropriate deallocation one would need,
– Calling
deleteon avoidpointerA code example:
Calling
deleteon avoidpointer as in above example, will cause a memory leak and a Undefined Behavior.