Heap Buffer Overflows: Causes, Detection and Prevention
A heap buffer overflow writes past a malloc block into the next chunk. Learn the common causes in C, how AddressSanitizer and Valgrind find them, and fixes.

A heap buffer overflow is a write, or a read, past the end of a block returned by malloc. Unlike a stack overflow, it does not reach a return address. It lands on the next heap chunk: its data, or the allocator's own bookkeeping next to it. The program often keeps running for a long time with a corrupted structure, and the crash happens far from the bug, inside free or in an unrelated function that used the damaged object. This post covers where heap overflows come from, what they damage in glibc's allocator, and how to find them with AddressSanitizer and Valgrind. Examples target GCC 15, Valgrind 3.25 and glibc 2.41 on Linux 6.12.
What the heap looks like around a block
glibc's malloc serves each request from a chunk. A chunk carries a small header just before the pointer you receive, with the chunk size and flag bits, and chunks sit next to each other in memory. A freed chunk reuses its first bytes to hold list pointers.
| Region | Contents |
|---|---|
| chunk header (before your pointer) | size of this chunk plus flag bits, and the size of the previous chunk when it is free |
| user data | the bytes malloc returned |
| padding | rounding up to the allocator's alignment, 16 bytes on x86-64 |
| next chunk header | size and flags of the neighbor |
An overflow of a few bytes may fall into padding and do nothing visible. A longer overflow overwrites the next chunk's header, which free and malloc later read to decide how to coalesce or reuse memory. glibc validates some of these fields and aborts with messages such as free(): invalid next size (fast) or malloc(): corrupted top size, but the check happens when the allocator next touches the chunk, which can be much later than the bad write.
Common causes
Wrong size arithmetic.
malloc(n * sizeof(int))wherencame from input and the multiplication wrapped. The block is small, the loop writesnelements. Usecalloc(n, sizeof(int)), which checks the multiplication, or check it yourself.Off by one.
malloc(strlen(s))without the+ 1, as covered in the string post of this series.Trusting a length field. A parser reads a length from a file or packet and calls
memcpy(dst, src, len)wheredstwas sized from a different field.**A stale size after
realloc.** The code reallocates a smaller block but keeps writing with the old capacity.Structure confusion. Allocating
sizeof(struct small)and casting the pointer tostruct big *.Missing bounds on a loop that fills a heap array. Typically
<=instead of<, or an index taken from input.
A small overflow
This program allocates ten bytes and writes eleven with a hand-written loop:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *buf = malloc(10);
if (buf == NULL)
return 1;
for (int i = 0; i <= 10; i++) /* bug: writes buf[10] */
buf[i] = 'a' + i;
printf("%c\n", buf[0]);
free(buf);
return 0;
}Without instrumentation, this program prints a and exits normally on glibc, because malloc(10) returns a chunk with 24 usable bytes on x86-64, so the eleventh write lands in space the allocator reserved. That passing run is why heap overflows ship.
Build with AddressSanitizer, gcc -std=c17 -g -O1 -fsanitize=address -fno-omit-frame-pointer -o heap_overflow heap_overflow.c, and the same program stops at the bad write:
=================================================================
==40214==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000001a at pc 0x55f2d3a4a1d2 bp 0x7ffc1c9e8a40 sp 0x7ffc1c9e8a30
WRITE of size 1 at 0x60200000001a thread T0
#0 0x55f2d3a4a1d1 in main heap_overflow.c:10
#1 0x7f7e0a02a1c9 in __libc_start_call_main
0x60200000001a is located 0 bytes after 10-byte region [0x602000000010,0x60200000001a)
allocated by thread T0 here:
#0 0x7f7e0a4e7a57 in malloc
#1 0x55f2d3a4a17e in main heap_overflow.c:6
SUMMARY: AddressSanitizer: heap-buffer-overflow heap_overflow.c:10 in mainAddresses and process ids differ on each run. The three useful lines are the access (WRITE of size 1), the location (0 bytes after 10-byte region) and the allocation site. AddressSanitizer works by placing red zones around every allocation and checking a shadow memory map on each access, and the AddressSanitizer documentation describes the design. It slows a program by a factor that depends on the workload, so use it in tests and fuzzing, not in production builds.
Detecting it without recompiling
When you cannot rebuild, Valgrind's Memcheck runs the unmodified binary on a synthetic CPU and tracks which heap bytes are valid. Build with -g for line numbers and run valgrind ./heap_overflow:
==40301== Invalid write of size 1
==40301== at 0x10917C: main (heap_overflow.c:10)
==40301== Address 0x4a8d04a is 0 bytes after a block of size 10 alloc'd
==40301== at 0x484880F: malloc (vg_replace_malloc.c:446)
==40301== by 0x109155: main (heap_overflow.c:6)Memcheck catches overflows that touch the byte just past a block, because it marks that byte invalid. It runs much slower than native speed, and it cannot see an overflow that jumps over the red zone into another valid block, which AddressSanitizer has the same trouble with when the stride is large.
What an overflow can damage
The damage depends on what sits next to the block.
Another object's data. The neighbor might be a pointer, a length or a function pointer. Overwriting it changes program behavior without any crash. This is the common case in modern exploits.
The next chunk's header. Changing the size field can make
freemerge unrelated memory, hand out overlapping blocks later, or trip a consistency check and abort.A freed chunk's list pointers. If the neighbor is free, its first bytes are list links. Overwriting them can make a later
mallocreturn an attacker-chosen address, a technique that glibc has hardened over many releases, including safe-linking of the small-bin pointers in glibc 2.32.
Prevention
Compute sizes safely. Use
calloc(n, size)for arrays, or checkn > SIZE_MAX / sizebefore multiplying. In C23 you can useckd_mulfrom<stdckdint.h>.Carry the capacity with the pointer. Pass
(ptr, cap)pairs, or wrap them in a struct, and check every index againstcap.Validate lengths from input against the size of the destination, not against a constant that might drift.
Use bounded copies.
memcpywith a checked length,snprintffor text.Test with sanitizers. Run the unit tests and fuzzers under
-fsanitize=address,undefined.Use a hardened allocator in production when the cost fits: Scudo and
hardened_mallocadd guard regions, randomization and quarantine, and GWP-ASan samples a fraction of allocations onto guarded pages so field crashes name the bug. A later post in this series covers them.Consider a safer language for new parsing code. The Rust post in this subcluster explains what the compiler enforces.
Reading a real crash
Production crashes from heap overflows rarely look like the examples above. The usual signatures are an abort inside free or malloc with a message about corrupted size or double list pointers, a segmentation fault when dereferencing a pointer that was overwritten with text, or a crash in code that has nothing to do with the buggy function. When the evidence is a core file, look at the heap object near the crash for text or patterns in fields that should hold numbers. A field that holds 0x6161616161616161 is a buffer of a characters that ran over it, and the allocation site from AddressSanitizer or Valgrind on a reproduction gives you the writer.


