Open In App

What is Memory Leak? How can we avoid?

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C programming, data can be stored in either stack or heap memory. The stack stores local variables and parameters of the function while the heap is used for dynamic memory allocation during runtime.

Memory Leaks in C

In C, memory allocated dynamically using malloc(), calloc(), or realloc()) have to be manually freed using free() when no longer needed. Memory leak occurs when the program allocates memory dynamic memory but forgets to deallocate it. This memory remains allocated for the duration of the program and cannot be reused by other processes.

Example of Memory Leak

C
void f() {
  
  	// Allocate memory
    int* ptr = (int*)malloc(sizeof(int));

    // Return without freeing ptr
    return;
}

Memory for an array of 10 integers is allocated using malloc() in the function f(), but the memory is never freed. After returning from the function, we won't even have the pointer to the memory so we can free it later. This causes memory leak in the program.

Common Causes of Memory Leak

Following are the most common causes of memory leak in C:

  • Forget to Free: When dynamically allocated memory is not freed up by calling free then it leads to memory leaks. Always make sure that for every dynamic memory allocation using malloc() or calloc(), there is a corresponding free() call.
  • Losing Pointer: When a program changes a pointer pointing to dynamically allocated memory without first freeing it, the reference to that memory is lost, making it impossible to free, resulting in a memory leak.
  • Abnormal Termination: When the function or some other part of the program terminates abnormally, and the allocated memory may not be freed as the control might not reach the free() function call.

How to avoid memory leaks?

  • Pairwise Allocation and Deallocation: Always ensure that corresponding free() is present for each dynamically allocated memory block once it is no longer needed.
  • Handle Abnormal Terminations: Make sure you handle the abnormal termination of the functions such that it does not causes memory leaks.
  • Use memory analysis tools: Tools like Valgrind and AddressSanitizer can help detect memory leaks by analysing a program's memory usage during runtime.
  • Code review: Regular code reviews and static analysis tools can help spot potential issues related to memory management.
  • Avoid unnecessary allocations: Only allocate memory when necessary and ensure that every allocation has a corresponding deallocation.

Next Article

Similar Reads