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.

class Myclass{
    int *p;
    Myclass (int n){
        p = new int {n};  //Allocating space in heap, needs to be free when not used

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:

#include <iostream>
using namespace std;
class Myclass{
    int *p;
    Myclass (int n){
        cout << "Allocating Space"<< endl;
        p = new int {n};
    void displayData(){
        cout << "Data is: "<< *p <<endl;
        cout << "Deleting pointer" << endl;
        delete p;
int main()
    Myclass obj(100);


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

four − 4 =