Skip to main content
Be Bitwise

Memory Errors Taxonomy

Memory Safety & Debugging · Memory & Systems track

7 min read

In this module

Every Way Memory Can Go Wrong

Memory errors are the single largest class of security vulnerabilities in systems software. Knowing each type — how it crops up, why it's dangerous, how to catch it — matters whether you're writing safe code or pulling apart vulnerable code.

Key Concept

Most C and C++ memory bugs reduce to a small set of patterns: writing past a buffer, using freed memory, freeing the same pointer twice, leaking memory, or reading uninitialised data. Naming the pattern is the first step to spotting it.

Buffer Overflow

A buffer overflow happens when code writes past the end (or before the start) of an allocated memory region. Stack buffer overflows clobber adjacent local variables, saved frame pointers, and return addresses. Heap buffer overflows corrupt heap metadata and adjacent heap objects.

c
char buf[16];
strcpy(buf, user_input); // If user_input > 15 chars, overflow!

Buffer overflows bite because the overwritten data often carries control-flow information — return addresses, function pointers — that an attacker can redirect to run arbitrary code. They're the original exploitation primitive and still rampant in C/C++ codebases.

Use-After-Free

A use-after-free (UAF) happens when code touches memory through a pointer after that memory has been freed. By then the memory may have been re-allocated for something else, so the access reads or writes whatever now lives there.

c
struct Object *obj = malloc(sizeof(struct Object));
free(obj);
// ... later ...
obj->field = value; // Use-after-free: obj points to freed memory

UAF is particularly nasty because an attacker can choose what occupies the freed memory. By triggering an allocation of the same size between the free and the use, they slot their data into the old object's slot. When the program accesses the "object," it reads the attacker's data instead.

Double-Free

A double-free frees the same memory twice. The repeat trip wrecks the allocator's internal data structures (free lists, bin pointers), potentially handing an attacker control over future allocations.

c
free(ptr);
// ... some code that does not set ptr to NULL ...
free(ptr); // Double-free!

In ptmalloc2 (glibc's allocator), freeing the same fastbin chunk twice in a row is caught by a check against the bin's top entry, and since glibc 2.29 the tcache spots repeats as well. Attackers get round the fastbin check by freeing something else in between, as in free(a); free(b); free(a); (with the tcache for that size already full). That puts a cycle in the fastbin list: the same chunk shows up twice, so two later mallocs return the same address, two objects sharing one memory location.

The Danger of Dangling Pointers

Both use-after-free and double-free stem from the same root cause: a dangling pointer - a pointer that still holds the address of freed memory. Defensive programming practices include setting pointers to NULL after freeing (preventing use-after-free from succeeding silently, though it causes a crash instead) and using smart pointers in C++ (which automatically manage lifetimes).

Memory Leaks

A memory leak happens when allocated memory becomes unreachable by any pointer in the program, leaving you unable to free it. The memory stays wasted until the process exits. In long-running programs (servers, daemons), leaks pile up over time and eventually drain available memory.

c
void process_request() {
char *buf = malloc(1024);
if (error_condition) return; // Leak! buf is never freed
// ... use buf ...
free(buf);
}

Most leaks aren't directly exploitable, but they can cause denial of service by exhausting memory. They also make programs unpredictable: behaviour drifts over time as memory pressure climbs.

Uninitialised Read

An uninitialised read uses a variable's value before it's been assigned. In C, local variables and malloc'd memory aren't auto-initialised. Their contents are whatever happened to live in that memory beforehand — sometimes sensitive data from earlier operations.

c
int x;
if (x > 0) { // Uninitialized read: x has an indeterminate value
// ...
}

Uninitialised reads leak information (leftover data from earlier operations), cause non-determinism (values shift between runs), and sometimes open the door to exploitation by letting an attacker control what previously sat in that memory.

Type Confusion

Type confusion happens when memory allocated for one type gets accessed as a different, incompatible type. The bytes get re-interpreted under the wrong layout.

cpp
Base *ptr = get_object();
Derived *d = static_cast<Derived*>(ptr); // Assumes ptr points to Derived
d->derived_field = value; // If ptr is actually a Base, this writes to wrong offset

Type confusion is rife in C++ (botched downcasts), JavaScript engines (JIT-compiled type assumptions that turn out wrong), and any code juggling void pointers or unions. Attackers ride type confusion to read or write memory at controlled offsets, or to redirect virtual function calls.

How Each Error Arises

A common thread runs through these errors: the C/C++ type system and memory model don't enforce safety invariants at runtime. The language trusts the programmer to keep arrays in bounds (no buffer overflow), avoid touching freed memory (no UAF), free memory exactly once (no double-free), eventually free everything (no leaks), initialise before reading (no uninit read), and keep casts type-safe (no type confusion).

When the programmer drops one of those invariants, the behaviour is undefined. The program can do anything — and attackers turn "anything" into control.

Name That Bug

Each snippet below has exactly one of the six errors from this lesson. Name it and think of a one-line fix before you open the answers.

c
/* 1 */ char name[8];
strcpy(name, "Alexander");
/* 2 */ char *line = malloc(80);
free(line);
printf("%s\n", line);
/* 3 */ int total;
for (int i = 0; i < n; i++) total += v[i];
/* 4 */ char *tmp = strdup(s);
if (len == 0) return -1;
free(tmp);
/* 5 */ void *p = malloc(32);
free(p);
cleanup(p); /* cleanup() also calls free(p) */
/* 6 */ struct shape *s = make_circle();
struct square *sq = (struct square *)s;
sq->side = 4;
Show the answers
  1. Buffer overflow. "Alexander" needs 10 bytes including the terminator and name has 8. Fix: size the buffer properly, or use snprintf(name, sizeof name, "%s", ...), which truncates.
  2. Use-after-free. line is read after it's freed. Fix: move the printf above the free, then set line = NULL.
  3. Uninitialised read. total starts with whatever was on the stack. Fix: int total = 0;.
  4. Memory leak on the early-return path. Fix: free(tmp) before returning, or check len before calling strdup.
  5. Double free, hidden inside a helper. Fix: decide which code owns the pointer and free it in one place; setting p = NULL after the first free makes the second one harmless.
  6. Type confusion. A circle is being written through a square pointer, so side lands at whatever offset a square keeps it. Fix: check the object's real type (a tag field, or dynamic_cast in C++) before casting.