What is a Memory Leak in C++ ?

In this article we will discuss what is Memory Leak C++ and why its harmful for applications.

Memory Leak

Memory leak in is a kind of Bug that kills your application slowly by first making it slow and then eventually crashing it.

How Does Memory Leak happens:

It happens in application when a programmer allocates the memory from heap for some temporary use and then forgets to delete this after using.

Take a look at following code,

#include <iostream>

void dummy()
    int * ptr = new int(5);


int main()
    return 0;

Here, inside the dummy() function we allocated 4 bytes on heap but forgot to delete that before returning from the dummy() function.
Also this dummy function didn’t exposed the pointer to that allocated memory, so nobody outside that dummy() have access to that allocated memory.

Hence calling dummy() function will result in memory leak.

Why Memory Leaks are harmful ?

Just chill, we waisted 4 bytes, but how does that matter that were just 4 bytes !!!


[showads ad=inside_post]


Wait a minute, what if someone called that dummy function 100000 times in an application.

Take a look at following code,

for(int i = 0; i < 100000; i++)

So, now 400000 Bytes of memory was leaked due to that memory leak.

Therefore, memory leaks are very serious bugs as it can make your application starve for memory i.e. make it very slow in response and
eventually crashes the application due to lack of memory.


2 thoughts on “What is a Memory Leak in C++ ?”

  1. Nice Introduction about Memory Leaks.

    So could you write a topic about how to detect and what are best practices to avoid Memory Leaks ?

    Thank you.

    1. This is something about which compiler will not warn you. So one should have:
      1. Debugger
      2. Proficiency in C++

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top