Google News
logo
Embedded C - Interview Questions
When does a memory leak occur? What are the ways of avoiding it?
Memory leak is a phenomenon that occurs when the developers create objects or make use of memory to help memory and then forget to free the memory before the completion of the program. This results in reduced system performance due to the reduced memory availability and if this continues, at one point, the application can crash. These are serious issues for applications involving servers, daemons, etc that should ideally never terminate.
 
Example of Memory Leak :
#include <stdlib.h>
 
void memLeakDemo()
{
   int *p = (int *) malloc(sizeof(int));
 
   /* Some set of statements */
 
   return; /* Return from the function without freeing the pointer p*/
}
 
In this example, we have created pointer p inside the function and we have not freed the pointer before the completion of the function. This causes pointer p to remain in the memory. Imagine 100s of pointers like these. The memory will be occupied unnecessarily and hence resulting in a memory leak.
 
We can avoid memory leaks by always freeing the objects and pointers when no longer required. The above example can be modified as:
#include <stdlib.h>;
 
void memLeakFix()
{
   int *p = (int *) malloc(sizeof(int));
 
   /* Some set of statements */
 
   free(p); // Free method to free the memory allocated to the pointer p
   return;
}
Advertisement