What is a memory leak in C and how to avoid it?

A memory leak happens when the program allocates memory with malloc(), calloc() or realloc() but never frees it. The program keeps using more and more memory, and a long running program can finally crash.

void leak(void) {
    int *p = malloc(100 * sizeof(int));
    // no free(p) here, and the pointer p is lost when the function ends
}

How to avoid it:

  • Call free() for every malloc().
  • Free the memory on all paths, also on the error paths.
  • Set the pointer to NULL after freeing.
  • Use tools like Valgrind or the AddressSanitizer (-fsanitize=address) to find leaks.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.