The Wayback Machine - https://web.archive.org/web/20210315091150/https://www.geeksforgeeks.org/what-is-memory-leak-how-can-we-avoid/
Skip to content
Related Articles

Related Articles

What is Memory Leak? How can we avoid?
  • Difficulty Level : Easy
  • Last Updated : 14 Jul, 2017

Memory leak occurs when programmers create a memory in heap and forget to delete it.
Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.




/* Function with memory leak */
#include <stdlib.h>
  
void f()
{
   int *ptr = (int *) malloc(sizeof(int));
  
   /* Do some work */
  
   return; /* Return without freeing ptr*/
}


To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.




/* Function without memory leak */
#include <stdlib.h>;
  
void f()
{
   int *ptr = (int *) malloc(sizeof(int));
  
   /* Do some work */
  
   free(ptr);
   return;
}


Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :