What is Memory Leak in C

In C programming, memory is managed manually using functions like `malloc()`, `calloc()`, `realloc()`, and `free()`. A memory leak occurs when a program allocates memory on the heap but fails to release it after use.

Memory leaks lead to wastage of memory resources, reduced performance, and can eventually cause the program or system to crash if leaks accumulate over time.

Causes of Memory Leak

- Allocating memory dynamically but never calling `free()` to release it.

- Losing the reference to allocated memory (e.g., overwriting a pointer before freeing it).

- Frequent allocation in loops without proper deallocation.

- Improper memory handling in complex data structures like linked lists, trees, or graphs.

Example of Memory Leak

C
Memory leak example
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = (int*) malloc(sizeof(int) * 5);

    if(ptr == NULL) {
        printf("Memory not allocated.\n");
        return 1;
    }

    ptr[0] = 10; // Use allocated memory

    ptr = NULL; // Lost reference to allocated memory without freeing it

    // Memory allocated above is now leaked

    return 0;
}

In this example, the allocated memory is never freed. Assigning `ptr = NULL;` causes the program to lose access to the memory, resulting in a memory leak.

How to Prevent Memory Leaks

- Always pair `malloc()`, `calloc()`, or `realloc()` with `free()` after the memory is no longer needed.

- Avoid losing pointer references; use temporary pointers if necessary.

- Use memory debugging tools like Valgrind to detect memory leaks during development.

- Be careful with loops that allocate memory multiple times; ensure proper deallocation each time.

- For complex data structures, implement proper cleanup functions that free all allocated nodes or elements.

Notes

- Memory leaks are a common problem in C due to manual memory management.

- Even small leaks can accumulate over time in long-running programs, leading to performance degradation.

- Using `free()` correctly and careful pointer management are key to preventing memory leaks.

Conclusion

Memory leaks occur when allocated memory is not properly deallocated, wasting system resources. Understanding causes and using best practices like freeing memory, avoiding lost references, and using debugging tools helps in writing efficient and reliable C programs.