C Lesson 23 – Memory Leaks | Dataplexa

Memory Leaks in C

You now know how to allocate memory and free it.

This lesson explains what happens when memory is not handled correctly.

Memory leaks are one of the most common and dangerous problems in C programs.


What Is a Memory Leak?

A memory leak occurs when:

  • Memory is allocated
  • The program loses access to it
  • The memory is never freed

The program continues running, but memory usage keeps increasing.


Why Memory Leaks Are Dangerous

Memory leaks cause:

  • Slow performance
  • High memory usage
  • Program crashes
  • System instability

In long-running programs, even small leaks become serious problems.


Common Cause #1: Forgetting free()


int *ptr = (int*) malloc(5 * sizeof(int));
/* memory used */

If free(ptr) is never called, the memory is leaked.


Common Cause #2: Losing the Pointer


int *ptr = (int*) malloc(5 * sizeof(int));
ptr = NULL;

The allocated memory still exists, but there is no way to free it.

This memory is permanently leaked.


Common Cause #3: realloc Misuse


ptr = realloc(ptr, new_size);

If realloc fails and returns NULL, the original memory is lost if not handled safely.

Correct approach:


int *temp = realloc(ptr, new_size);
if (temp != NULL) {
    ptr = temp;
}

Common Cause #4: Double free()


free(ptr);
free(ptr);

This leads to undefined behavior and program crashes.


Best Practices to Avoid Memory Leaks

  • Always free what you allocate
  • Set pointer to NULL after free()
  • Check realloc return value
  • Use consistent ownership rules

Real-World Analogy

Memory leaks are like:

  • Renting rooms
  • Forgetting where the keys are
  • Never returning the rooms

Soon, there are no rooms left.


Mini Practice

  • Allocate memory for an integer array
  • Use it
  • Free it
  • Set pointer to NULL

Quick Quiz

Q1. What is a memory leak?

Allocated memory that is never freed.

Q2. Is forgetting free() a memory leak?

Yes.

Q3. Why set pointer to NULL after free()?

To prevent accidental reuse.

Q4. Can realloc cause memory leaks?

Yes, if used incorrectly.

Q5. Are memory leaks visible immediately?

No, they grow over time.