Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 135 ยท Memory Management

Memory Errors

Learn the classic C memory bugs - leaks, double free, use-after-free, buffer overruns and uninitialized reads - how Valgrind and AddressSanitizer find them, and safe habits.

In the previous lesson you learned the four allocation functions and the patterns for using them correctly. This lesson is about what happens when those patterns slip. Memory errors are the most famous class of C bugs, and for good reason: studies of large C and C++ codebases (browsers, operating systems) regularly find that around two thirds of serious security vulnerabilities are memory-safety bugs.

What makes them dangerous is not that they crash. A crash is the good outcome. The real problem is that most memory errors are undefined behavior: the program may print the right answer today, the wrong answer tomorrow, and hand an attacker control of the machine next month. The compiler doesn't insert checks for you, so you need three things: an understanding of each bug, coding habits that prevent them, and tools that find the ones that slip through.

Warning: the examples in this lesson never actually execute a memory error, because the output of undefined behavior can't be trusted or reproduced. Where a function contains a bug on purpose, the program compiles it (so you can see the compiler's warning) but doesn't call it.

The five classic bugs

Bug What happens Typical cause
Memory leak Memory is never freed Losing the last pointer, early return, forgotten cleanup
Double free The same block is freed twice Two owners, freeing in a loop and again after it
Use after free A freed block is read or written Dangling pointers, stale copies, realloc moving data
Buffer overrun Access outside an allocated block or array Off-by-one loops, missing room for '\0', unchecked lengths
Uninitialized read A variable or malloc block is read before it's written Forgotten initializer, partial initialization

Let's look at each, then at the tools.

Memory leaks

A leak happens when you lose every pointer to a heap block without freeing it. The block stays allocated until the process exits. One leaked string is harmless; a leak inside a loop that runs for hours, in a server or a phone app, eventually exhausts memory.

C
void greet(const char *name)
{
    size_t size = strlen(name) + 8;     /* "Hello, " + name + '\0' */
    char *message = malloc(size);
    if (message == NULL) {
        return;
    }
    snprintf(message, size, "Hello, %s", name);
    if (name[0] == '\0') {
        return;                 /* leak: message is never freed */
    }
    puts(message);
    free(message);
}

The early return is the most common source of leaks in real code. Every exit path must release what the function owns. Two fixes work well: restructure so there's a single exit, or use the goto cleanup pattern from break, continue and goto, where every error path jumps to one block that frees everything.

A leak isn't undefined behavior, so you can safely detect it from inside a program. Here's a tiny tracking layer that counts allocations and frees. Real projects use tools instead, but writing one yourself shows exactly what a leak checker is looking for:

C Catching a leak with counting wrappers

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.

The program reports blocks still allocated: 2, one for each short word ("to" and "go") that took the early return. Add tracked_free(copy); before return 0; and the count drops to 0. Some teams keep wrappers like these in debug builds, which is cheap and catches leaks in tests.

Double free

Freeing the same pointer twice corrupts the heap allocator's internal bookkeeping. Modern C libraries often detect simple cases and abort with a message like free(): double free detected, but you can't count on it, and heap corruption has been the starting point for many real exploits.

Double frees usually come from unclear ownership: two parts of the program each believe they own a block. The structural fix is to decide on one owner. The tactical fix is to set the pointer to NULL right after freeing, because free(NULL) does nothing. A small helper that takes the address of the pointer can do both at once (this uses a pointer to a pointer):

C free_and_null makes a second free harmless

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.

The limit of this trick: it only resets that variable. If you copied the pointer into a struct or another variable earlier, those copies still dangle. Nulling pointers is a safety net, not a substitute for clear ownership.

Use after free

Reading or writing a block after freeing it is called use after free. The memory might still hold the old values (so the bug hides), or the allocator might already have handed it to another part of the program (so you silently read or overwrite someone else's data). In security reports, use-after-free is one of the most exploited bug classes.

The typical shapes are:

  • Using a pointer after passing it to free, often in an error-handling path.
  • Keeping a second pointer to the same block (an alias) after the owner freed it.
  • Keeping a pointer into an array that realloc later moved.
  • Returning the address of a local variable: not a heap bug, but the same idea, since the stack frame is gone after the function returns.

GCC can spot the simplest cases at compile time. The next program contains two buggy functions that are compiled but never called. Run it and read the compiler's warnings:

C Warnings the compiler can give you

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.

GCC 15 reports pointer 'p' used after 'free' [-Wuse-after-free] on line 13 and an -Warray-bounds warning about the strcpy on line 19, saying the copy goes out of the bounds of label. These warnings come from -Wall and the optimizer's analysis, which is one more reason to always compile with warnings on (see How C Works).

Don't be lulled, though. The compiler sees only patterns it can prove inside one function. Pass the pointer through another function, store it in a struct, or free it on one branch and use it on another, and the warning usually disappears while the bug remains.

Buffer overruns

A buffer overrun (or overflow) reads or writes past the end, or before the start, of an array or heap block. C has no bounds checks, so a[10] on a 10-element array compiles fine and touches whatever memory is next. A write can corrupt other variables, the allocator's metadata or, on the stack, a function's saved return address, which is the classic "stack smashing" attack.

The commonest causes are:

  • Off-by-one loops: for (int i = 0; i <= n; i++) on an n-element array.
  • Forgetting the terminator: allocating strlen(s) bytes instead of strlen(s) + 1 for a copy.
  • Trusting input lengths: copying user data with strcpy, sprintf or unbounded scanf("%s"), all covered in Safe String Handling.
  • Wrong size arithmetic: malloc(n) instead of malloc(n * sizeof *p).

The defensive habit is to keep the size next to the pointer and check indexes wherever data comes from outside your control:

C A bounds-checked accessor

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.

Index 4 is the classic off-by-one: valid indexes run from 0 to length - 1. Because size_t is unsigned, a single index >= length comparison also rejects "negative" values that wrapped around to huge numbers.

Uninitialized reads

Local variables and malloc memory start with indeterminate contents. Reading them before writing is undefined behavior, not just "a random number". Optimizers really do exploit this: with GCC at -O1, a variable that's only assigned on one branch may simply be treated as if it always had that value, so the bug never shows up in testing.

C
int sum(const int *values, int count)
{
    int total;                  /* BUG: should be int total = 0; */
    for (int i = 0; i < count; i++) {
        total += values[i];
    }
    return total;
}

GCC flags this one with 'total' may be used uninitialized [-Wmaybe-uninitialized]. The fixes are simple: initialize every local where you declare it, use calloc or memset when a block must start at zero, and initialize arrays and structs with = {0} (or = {} in C23).

Tools that find memory errors

You can't test your way out of undefined behavior by just looking at output. Use tools that watch every memory access.

AddressSanitizer (ASan) is built into GCC and Clang. You compile with an extra flag, and the program aborts with a detailed report at the first bad access:

Terminal
gcc -std=c17 -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer main.c -o app
./app

A report looks roughly like this (shortened):

TEXT
==4120==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000010
READ of size 4 at 0x502000000010 thread T0
    #0 0x401234 in read_after_free main.c:13
    #1 0x401300 in main main.c:25
freed by thread T0 here:
    #0 0x7f... in free
    #1 0x401220 in read_after_free main.c:12

It tells you the kind of bug, the line that made the bad access and the line that freed the block. ASan also detects heap and stack overruns, double frees and, through LeakSanitizer, leaks at exit. Programs run about twice as slowly, which is fine for tests. -fsanitize=undefined (UBSan) adds checks for signed overflow, bad shifts and similar undefined behavior.

Valgrind (Linux, some macOS versions) needs no recompilation. It runs your existing program on a simulated CPU and checks every access, at the cost of being 10 to 50 times slower:

Terminal
valgrind --leak-check=full ./app
TEXT
==5311== Invalid read of size 4
==5311==    at 0x1091A6: read_after_free (main.c:13)
==5311==  Address 0x4a8e040 is 0 bytes inside a block of size 4 free'd
...
==5311== LEAK SUMMARY:
==5311==    definitely lost: 6 bytes in 2 blocks

On Windows, MSVC supports /fsanitize=address too. Neither tool is available in our online editor, so run them on your own machine; Debugging C Programs walks through a full session.

Tip: make sanitizers part of your routine, not an emergency tool. Build and run your tests with -fsanitize=address,undefined during development, and keep a normal optimized build for release.

Habits that prevent memory errors

  • One owner per block. Write down (in a comment or the function name) who frees each allocation. Functions named *_create / *_destroy or *_new / *_free make pairs obvious.
  • Allocate and free at the same level. If a function allocates something purely for its own work, it should free it before every return.
  • Single exit with goto cleanup for functions that acquire several resources.
  • Keep sizes with pointers. Pass (pointer, length) pairs or put both in a struct, and check indexes from untrusted input.
  • Initialize at declaration, and prefer calloc when zero is a meaningful start.
  • Null after free when the pointer stays in scope.
  • Compile with -Wall -Wextra and test with sanitizers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A function mallocs a buffer, then returns early when its argument is empty, before reaching free. What kind of bug is this?

    The only pointer to the block is a local variable that disappears on return, so the block can never be freed.
  2. 2. After free(p); p = NULL; the code calls free(p); again. What happens?

    p is NULL at the second call, and free(NULL) is defined to do nothing. Other copies of the old pointer would still dangle, though.
  3. 3. int *a = malloc(5 * sizeof *a); then for (int i = 0; i <= 5; i++) a[i] = 0; What is wrong?

    The condition i <= 5 runs six times. Valid indexes are 0 to 4, so a[5] is a buffer overrun.
  4. 4. A program prints the correct result in every test, but Valgrind reports an invalid read. What should you conclude?

    Undefined behavior can appear to work. Correct output proves nothing; the invalid read is a real bug.
  5. 5. Why can't you rely only on compiler warnings such as -Wuse-after-free?

    Warnings are static and limited. Runtime tools like AddressSanitizer and Valgrind watch the actual accesses.

Summary

  • The five classic memory bugs are leaks, double frees, use after free, buffer overruns and uninitialized reads. All but leaks are undefined behavior.
  • Undefined behavior can look correct in testing, so correct output is not proof of correct code.
  • Leaks come from lost pointers and early returns; fix them with clear ownership and a single cleanup path.
  • free(NULL) is a no-op, so setting pointers to NULL after freeing turns many double frees and use-after-free bugs into harmless or detectable ones.
  • Overruns come from off-by-one loops, missing space for '\0' and unchecked lengths; keep sizes with pointers and check indexes.
  • -Wall -Wextra catches some bugs at compile time; AddressSanitizer and Valgrind catch far more at run time. Use them while developing.

Next: Memory Layout of a C Program, where you'll see where code, globals, the heap and the stack actually live.