In this article we will discuss the difference between delete &  []delete and how mixing new [] with delete can give rise to Memory Leaks.

To allocate memory dynamically on heap we use new[] operator i.e.

Here new[] performs following operations internally,

  1. In first step, it will allocate the memory on heap equivalent to the size of 5 Objects of class Sample by calling operator new[].
  2. In second step, it calls the default constructor for each of the allocated object i.e. 5 Objects in this case.

To delete the memory allocated by new[] operator , we should not use delete operator because delete operator internally calls operator delete  to deallocate the memory and calling only 1 object’s destructor. Remaining 4 object’s destructor will not be called in this case, although memory will be deallocated. This can give rise to the problems of memory leaks.

Check out following example for memory leaks by mixing new[] and delete,

Here 5 objects of class Sample were allocated on heap by new[]
But as delete operator is used to delete the memory allocated by new[] operator, therefore destructor of only one object is called.
For remaining 4 objects destructor was not called, due to which m_ptr was not deleted for remaining objects and hence resulted in memory leak.

 

How to fix this memory leak caused by mixing new[] and delete ?

We should always use [] delete operator with new [] operator to delete the dynamically allocated array on heap.

  1. [] delete operator performs following operations internally,In first step, it calls the destructor for each of the allocated object i.e. 5 Objects in this case.
  2. In second step, it will de-allocates / deleted the memory from the heap equivalent to the size of 5 Objects of class Sample by calling operator delete[].

Now lets fix the above operator memory leak with [] delete operator,