What is Memory Leak? How can we avoid?

1.5

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;
}

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



1.5 Average Difficulty : 1.5/5.0
Based on 37 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.