What is Memory Leak? How can we avoid?

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right




My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.