What Is Memory leak in C++ and How to avoid it?

  • This happens when the programmers allocate memory to the heap for some temporary use and then forget to delete it after using it.
  • A memory leak occurs when a piece (or fragments) of memory previously allocated by a programmer is not properly deallocated by the programmer.
  • Even if it is not in use by the memory program, it is still “reserved”, and that piece of memory can not be used by the program until it is properly deallocated by the programmer. So it’s called memory leak.
  • Memory leak is a kind of bug that kills your app slowly by slowing down and eventually crashing it.

Memory leak Example:-

#include<iostream.h>

using namespace std;

void demo_memory_leak()

{

int* ptr = new int(5);

}




int main()

{

// Call the function demo_memory_leak() to show memory leak

demo_memory_leak();

return 0;

}

 

Here, within the function_memory_leak () function we have allocated 4 bytes on the heap, but forgot to release that memory before returning from function demo_memory_leak ().

Apart from this, this demo_memory_leak() function has not highlighted the pointer for that allocated memory, so no one outside the demo_memory_leak() has access to that allocated memory.

Therefore, the memory will leak by calling the demo_memory_leak () function.

 

Example to handle memory leaks:-

using namespace std;

// function to show memory handling

void demo_handle_mleak()

{

int* ptr = new int(5);

// Now delete pointer ptr using delete operator

delete (ptr);

}

int main()

{

// Call the function demo_handle_mleak() to handle the memory leak

demo_handle_mleak()

return 0;

}

Therefore, to match the new pointers in C ++, always write the delete pointers and always type the code between these new and delete operator  the explained in the above example.

In the above example, no memory is useless because when we are coming out of the function, we are deleting the memory using the delete operator

Leave a Reply

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