Memory in C/C++ is stored in stack and heap memory. A memory leak occurs when dynamically allocated heap memory is not released after it is no longer needed, causing unnecessary memory consumption.
- In C, memory is allocated using malloc()/calloc() and released using free(), while in C++, new/new[] is paired with delete/delete[].
- Memory leaks can degrade performance and may eventually crash long-running applications such as servers if the unreleased memory keeps accumulating.

Example of Memory Leak in C
The following example demonstrates a memory leak where memory is allocated dynamically using malloc() but is never released using free().
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Dynamically allocate memory
int *ptr = (int *)malloc(5 * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Use the allocated memory
ptr[0] = 10;
ptr[1] = 20;
printf("Values: %d %d\n", ptr[0], ptr[1]);
// free(ptr); // Memory is not released (Memory Leak)
return 0;
}
Output
Values: 10 20
Explanation
- Memory is allocated dynamically using malloc(), but free(ptr) is never called before the program terminates.
- Since the allocated memory is not released, it remains occupied, resulting in a memory leak.
Common Causes of Memory Leak
Memory leaks usually occur when dynamically allocated memory is not released properly, causing the allocated memory to remain occupied even after it is no longer needed.
- Forgetting to release allocated memory using free() or delete after allocation with malloc(), calloc(), or new.
- Overwriting a pointer or letting it go out of scope before freeing the memory it points to, making the allocated memory unreachable.
- In long-running applications, repeated memory leaks accumulate over time, increasing memory usage and reducing system performance.
Best Practices to avoid memory leaks
Memory leaks can be prevented by managing dynamically allocated memory carefully and releasing it when it is no longer required.
- Always release dynamically allocated memory using free() in C or delete/delete[] in C++ after use.
- Avoid overwriting pointers before freeing their previously allocated memory, and ensure every allocation has a corresponding deallocation.
- In C++, use smart pointers (unique_ptr, shared_ptr) and memory analysis tools like Valgrind to automatically manage and detect memory leaks.
Consequences of Memory Leaks
Memory leaks can significantly affect the performance, stability, and reliability of an application, especially in long-running programs.
- Memory leaks gradually consume available system memory, reducing the memory available for other processes.
- Excessive memory usage can slow down the application and degrade overall system performance.
- If memory continues to accumulate, the application may crash or generate Out of Memory errors.
- Long-running applications such as servers can become unstable or unresponsive due to continuous memory leaks.