Skip to content
Tutorials Center
My learning

Topics

C Reference ยท stdlib.h

C memory errors: leaks, double free, use after free

Reference for the common C heap errors: memory leaks, double free, use after free, buffer overflow and invalid free, with safe patterns and tools to find them.

C does not check memory use for you. When a program breaks the rules of malloc and free, the standard calls it undefined behavior: the program may crash, print garbage, appear to work today and fail tomorrow, or be exploitable by an attacker. Output from such a program proves nothing, so this page shows the broken patterns as read-only code and runs only the corrected versions.

The five classic errors are the leak, the double free, the use after free, the heap buffer overflow and the invalid free. All of them have the same root cause: losing track of who owns a block and how big it is.

C
int *p = malloc(sizeof *p);
free(p);
*p = 1;          /* use after free: undefined behavior */

The errors, with the bug shown read-only

C
/* 1. Leak: the only pointer is lost, the block can never be freed */
void leak(void) {
    char *buf = malloc(100);
    buf = NULL;                        /* block is still allocated, unreachable */
}

/* 2. Double free: the allocator's bookkeeping is corrupted */
void double_free(void) {
    int *p = malloc(sizeof *p);
    free(p);
    free(p);                           /* undefined behavior */
}

/* 3. Use after free: the memory may already belong to someone else */
void use_after_free(void) {
    int *p = malloc(sizeof *p);
    free(p);
    printf("%d\n", *p);                /* undefined behavior */
}

/* 4. Heap buffer overflow: writing past the end of the block */
void overflow(void) {
    char *s = malloc(4);
    strcpy(s, "overflow");             /* needs 9 bytes, wrote into the next block */
    free(s);
}

/* 5. Invalid free: not a pointer from malloc */
void invalid_free(void) {
    int local[4];
    free(local);                       /* undefined behavior */
    char *m = malloc(8);
    free(m + 1);                       /* not the start of the block */
}

Try it

C Fixing the leak: one owner, one free

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Defensive habits against double free and dangling pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Finding and preventing them

Error What goes wrong Typical prevention
Leak Memory is never returned; a long-running program grows until it dies. One clear owner per block; free on every path, including errors.
Double free Allocator metadata is corrupted; later calls crash or become exploitable. Set pointers to NULL after free; free in one place.
Use after free Reads stale or reused data; writes corrupt another object. Do not keep copies of freed pointers; narrow lifetimes.
Buffer overflow Neighbouring blocks or metadata are overwritten. Track sizes; use snprintf and fgets with a size; check indexes.
Invalid free Allocator is handed an address it never gave out. Free only the exact pointer returned by malloc.

Usage notes

  • Undefined means unreliable, not "always crashes". A use after free often seems to work because the freed memory still holds the old bytes. That is the dangerous case.
  • Use the tools. Compile test builds with -fsanitize=address,undefined -g; run Valgrind on Linux. They report the line of the allocation, the free and the bad access. The in-browser runner does not run them, which is another reason this page keeps the faulty code read-only.
  • Check for NULL after every allocation, and clean up partially built objects when a later allocation fails.
  • Single exit point. The goto cleanup; pattern (see free) keeps releasing code in one place.
  • Strings: the buffer needs strlen(s) + 1 bytes. This off-by-one is the most frequent overflow.
  • Ownership rules in the API. Document in comments whether a function returns a fresh block the caller must free, or a pointer into someone else's data. See Memory ownership patterns.
  • Do not log pointer values to prove that two blocks differ; compare with == only, and treat printed addresses as run-specific.