Summary: In this tutorial, we will learn what memory leak is when it occurs and how can we avoid it in C++.

What is a Memory leak?

When we use a new operator with raw pointers in our program, we actually are allocating space for it in the heap memory.

This space in the memory remains occupied until freed manually.

The ideal point for freeing this space is when the pointer is no longer of use or out of scope.

If we don’t and the pointer is destroyed, space remains occupied in the memory, causing a memory leak.

For example: Suppose you have a class with a raw pointer as one of its properties and you create an object of this class.

Once you are finished using the object it will be destroyed at the end of the program or scope.

Memory Leak in C++

But what’s to be noted is that the memory you’ve used for the pointer is still containing data but can no longer be accessed.

This inaccessible memory is termed as a memory leak.

How to Avoid Memory Leak?

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 in the destructor of the class.

The destructor of the class is called whenever its object is destroyed or goes out of scope.

Here is the example in C++ that shows the deletion of the pointer (allocated memory) with the use of destructors:


what is memory leak

To avoid memory leaks while using raw pointers, we have to manually delete them.

It is best to use smart pointers in such cases because we don’t need to explicitly free up the allocated space in the heap.

That’s all for the memory leaks explanation. Comment below if you have any doubts.

Leave a Reply

1 × 3 =