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,

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 !!!

 

 

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

Take a look at following code,

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.

Thanks.

Click Here to Subscribe for more Articles / Tutorials like this.