What is a memory leak c++: In the previous article, we have discussed about Find all occurrences of a sub string in a string | CPP | Both Case Sensitive & InSensitive. Let us learn What is a Memory Leak in C++ Program.
Memory Leak in C++
In this article we discuss about memory leak and why it is harmful for any application.
We will see one by one.
Memory Leak :
Memory leak refers to the unused reserved memory space. Means when a programmer allocates a piece of memory for some valid purposes but later forgets to deallocate properly then that memory is no longer used by the programmer and remains allocated for no use. That is called as memory leak. So simply it refers to no longer needed memory which is not released and it is a type of resource leak. So every programmer while working with any project should take care of this memory leak.
How Does Memory Leak happens :
In C++ when a programmer allocates memory by using new
keyword for its use but forgets to deallocate the same memory by using delete()
function or delete[]
operator after use creates memory leak.
Let’s go through an example
#include <iostream> void sample() { // Memory allocated using new keyword int * ptr = new int(5); } int main() { // sample method called sample(); return 0; }
In the above example we saw that inside sample()
method we allocated 4 bytes on heap but forgot to delete that memory before returning from sample()
method. So when sample()
method will be called memory leak will occur.
How it is harmful ?
Here only 4 bytes wasted but think about a situation like this where a lot memory space will be wasted.
Suppose that sample method is called 100000 times in an application. Then 400000 Bytes of memory leak will occur.
So memory leak has a bad effect on any application as it hold memory unnecessarily, will make the application slow in providing response as well as it may crashes the application. So for a better application performance and smooth usability of application taking care of memory leak is very important.