On using raw pointers in C++ we also need to take care of deleting the pointer, it could cause a memory leak.

What is memory leak?

Suppose you have a class with a raw pointer as variable and you create an object of that class. Once you are done using the object it will be destroyed at the end of the program or scope.

But the point to note is that the memory which you have used to for pointer is still there containing the data but now can’t be accessed. This unfreed, inaccessible memory is termed as a memory leak.

Memory Leak in C++

How to avoid Memory Leaks?

There are two possible ways to avoid :

  1. To properly delete the pointers when it is of no use
  2. By using Smart Pointers

The best place to delete pointers is Destructor of the class. The Desctructor of the class is called each time when its object is destroyed or when it goes out of scope.

Here is the program which illustrates the delete/free of pointer/allocated memory with the use of destructors.

what is memory leak

To avoid memory leaks in C++ use of smart pointers is the best method because it does not require us to explicitly free up allocated space in heap i.e deletion of the pointer. That’s all for the memory leaks explanation. If you have any doubt then do comment below.

 

Leave a Reply

Close Menu