Skip to main content

Lesson 4 of 5

free - Dangling Pointers, Double-free & Memory Leaks

`free(ptr)` returns heap memory to the allocator. Three critical bugs: **dangling pointer** (using memory after `free`), **double-free** (calling `free` twice on the same pointer - corrupts the heap allocator's metadata), and **memory leak** (failing to call `free` before the last pointer goes out of scope). All three are undefined behaviour and real-world security vulnerabilities.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

The Three Heap Bugs - With Valgrind Identification

The Three Heap Bugs - With Valgrind Identification
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* ── Bug 1: Use After Free (dangling pointer) ────────────── */
void use_after_free_demo(void) {
    int *p = malloc(sizeof(int));
    if (!p) return;
    *p = 42;
    free(p);
    /* p now DANGLING - points to freed memory               */
    /* printf("%d
", *p);  ← UB: may print garbage, may crash */
    /* *p = 99;             ← UB: may corrupt heap metadata  */

    /* Fix: null after free */
    p = NULL;
    /* *p = 99;  ← still UB, but now: crash immediately (SIGSEGV)
       This is BETTER than silent corruption.               */
}

/* ── Bug 2: Double Free ──────────────────────────────────── */
void double_free_demo(void) {
    char *buf = malloc(100);
    if (!buf) return;
    strcpy(buf, "hello");
    free(buf);
    /* free(buf);  ← double free: corrupts allocator metadata
                     May crash immediately or much later     */
    buf = NULL;   /* prevents double free */
    free(buf);    /* free(NULL) is a safe no-op - guaranteed by C standard */
}

/* ── Bug 3: Memory Leak ──────────────────────────────────── */
void memory_leak_demo(int n) {
    int *arr = malloc((size_t)n * sizeof(int));
    if (!arr) return;
    /* ... process arr ... */
    if (n > 100) {
        /* 'return' without freeing arr = LEAK */
        return;   /* WRONG: arr is lost */
    }
    free(arr);    /* Only freed for n <= 100 */
}

void memory_leak_fixed(int n) {
    int *arr = malloc((size_t)n * sizeof(int));
    if (!arr) return;
    /* ... process arr ... */
    free(arr);   /* Always freed before return */
}

/* ── Valgrind output examples ────────────────────────────────
   Run: valgrind --leak-check=full ./program

   == MEMORY LEAK:
   40 bytes in 1 blocks are definitely lost in loss record 1 of 1
     at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload)
     by 0x10873F: memory_leak_demo (main.c:28)
     by 0x108763: main (main.c:40)

   == INVALID READ (use-after-free):
   Invalid read of size 4
     at 0x108709: use_after_free_demo (main.c:13)
   Address 0x522D040 is 0 bytes inside a block of size 4 free'd
     at 0x4C30D3B: free (vgpreload)

   Run: -fsanitize=address,undefined for faster detection     */

int main(void) {
    use_after_free_demo();
    double_free_demo();
    memory_leak_demo(50);   /* leaks nothing: n <= 100 */
    memory_leak_demo(150);  /* leaks 600 bytes          */

    printf("Program completed (with intentional bugs for demo)
");
    return 0;
}

/* ── The ownership contract ────────────────────────────────
   For every malloc, exactly one free must be called.
   The code that CREATES the allocation OWNS it.
   Pass ownership explicitly via naming conventions:
   - Functions named alloc_xxx() CREATE - caller must free.
   - Functions named destroy_xxx() CONSUME - do not use after.
   - Functions named borrow_xxx() READ-ONLY - no ownership.   */

Common Mistakes

  • Not setting pointer to NULL after free - leaves a dangling pointer that compares non-NULL but points to freed memory. All subsequent reads/writes are undefined. Immediately: `free(p); p = NULL;`.
  • Freeing stack memory - `int x = 5; free(&x);` - you cannot free stack memory with `free`. Only pass `malloc/calloc/realloc`-returned pointers to `free`. Passing any other address is undefined behaviour.
  • Memory leak in error paths - always audit every `return` and `goto cleanup` path in a function to ensure all allocations made before that point are freed. Use the `goto cleanup` pattern from Module 2.

Tip

Tip

Practice free Dangling Pointers Doublefree Memory Leaks in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Always pair every malloc with free and set released pointers to NULL

Practice Task

Note

Practice Task - (1) Write a working example of free Dangling Pointers Doublefree Memory Leaks from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with free Dangling Pointers Doublefree Memory Leaks is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • `free(ptr)` returns heap memory to the allocator.
  • Not setting pointer to NULL after free - leaves a dangling pointer that compares non-NULL but points to freed memory. All subsequent reads/writes are undefined. Immediately: `free(p); p = NULL;`.
  • Freeing stack memory - `int x = 5; free(&x);` - you cannot free stack memory with `free`. Only pass `malloc/calloc/realloc`-returned pointers to `free`. Passing any other address is undefined behaviour.
  • Memory leak in error paths - always audit every `return` and `goto cleanup` path in a function to ensure all allocations made before that point are freed. Use the `goto cleanup` pattern from Module 2.

Topics in This Module

0/5 done