Memory Leak in C

Shilpa S Jadhav
2 min readApr 30, 2021

When programmer allocates the piece of the memory dynamically and forget to release/free the memory i.e called as Memory Leak.In other words, you have reserved the memory which is no longer used by the program.

Memory leaks causes serious issues in some of the cases. For example in servers where server never terminates OR in a program you are requesting for the memory such as shared memory and that is not released even program terminates.

Here is an example:

#include <stdlib.h>

/* Function with memory leak */
int fun(){
int *ptr = (int*)malloc(sizeof(int));
/* Do some operations */
return 0; /*Returning without freeing the ptr */
}

/* Function without memory leak */
int fun(){
int *ptr = (int*)malloc(sizeof(int));
/* Do some operations */
free(ptr);
return 0;
}

How to detect the memory leak

Use Valgrind tool,

% valgrind --tool=memcheck --leak-check=yes <pgm_name>

You can explore more on Valgrind tool to check for more options

Some precaution to avoid memory leak,

  1. Always de-allocate or free the memory which is allocated by the programmer
  2. Sometimes we required allocated memory through out the application, in that situation we have to write the free() function in the handler that will invoke at the end of the application

If you can think of any other techniques to avoid memory leak please feel free to mention in comments.

Comments or suggestions are always welcome.

Thank You.

--

--