Pointers & Memory · intermediate · ~8 min

Memory leaks

Follow ownership across branches and distinguish a counter model from actual leak detection.

Overview

A leak occurs when allocated storage is no longer reachable for its intended cleanup. A simple allocation/free trace helps you practice accounting, but matching counts alone cannot establish that a real program freed the right objects.

Core concepts

Draw one ownership obligation for each successful allocation. Follow success and error returns: every path must either release that ownership or transfer it to someone responsible for cleanup.

A trace using a for allocation and f for free is a simplified counter exercise. Real programs need object identities: freeing one object twice while forgetting another can produce balanced counts and still be wrong.

Use a memory checker when available and inspect ownership paths as well. Passing a few inputs is not proof that every error path releases its resources.

Lesson

A leak occurs when allocated storage is no longer reachable for its intended cleanup. A simple allocation/free trace helps you practice accounting, but matching counts alone cannot establish that a real program freed the right objects.

Code examples

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int *p = malloc(sizeof *p);
    if (p == NULL) return 1;
    *p = 5;
    int result = *p;
    free(p);
    printf("%d\n", result);
    return 0;
}

Expected output on a successful allocation, where applicable:

5

Line by line

Only a successful allocation creates a cleanup obligation. The successful path consumes that obligation before returning; the failure path owns no allocation.

Practice tasks

  1. Mark which branches acquire and release ownership.
  2. Complete Are allocations balanced?.
  3. Complete Count leaked allocations.
  4. Explain why counting alone cannot detect freeing object A twice while leaking object B.

Summary

Account for each successful allocation on every path. Trace counters are teaching models; real leak analysis tracks particular allocations and their owners.

Practice with these exercises