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.
class Sample; Sample * ptrArr = new Sample[5];
Here new[] performs following operations internally,
- In first step, it will allocate the memory on heap equivalent to the size of 5 Objects of class Sample by calling operator new[].
- 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,
[/#include <iostream> class Sample { int * m_ptr; public: Sample() { std::cout<<"Sample::Constructor\n"; m_ptr = new int(); } ~Sample() { std::cout<<"Sample::Destructor\n"; delete m_ptr; m_ptr = NULL; } }; int main() { Sample * ptrArr = new Sample[5]; // Calling delete on pointer that contains // memory allocated by new[] will cause only // one destructor, remaining 4 destructors // will not be called, hence memory leak. delete ptrArr; return 0; }
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.
[showads ad=inside_post]
Frequently Asked:
- How does new and delete operator works internally ?
- Unary Operator Overloading in C++ using both member & Friend function
- Allocating and deallocating 2D arrays dynamically in C and C++
- Designing Code to Convert the base of a Number to any other base in Number System
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.
- [] 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.
- 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,
#include <iostream> class Sample { int * m_ptr; public: Sample() { std::cout<<"Sample::Constructor\n"; m_ptr = new int(); } ~Sample() { std::cout<<"Sample::Destructor\n"; delete m_ptr; m_ptr = NULL; } }; int main() { Sample * ptrArr = new Sample[5]; // will call destructor of all 5 objects delete [] ptrArr; return 0; }