Dynamic Memory Management

a heap buffer overflow

You rented a locker sized for exactly 10 boxes, but you keep stacking until you have 12 — the last two spill over into the lockers next to yours, scrambling whatever your neighbors stored. A heap buffer overflow is writing (or reading) past the end of a block you allocated, so you touch memory that belongs to a different allocation, to the allocator's own bookkeeping, or to nothing valid at all.

Precisely: when you malloc(n) bytes, the only memory you are allowed to touch is the bytes at offsets 0 through n-1. Indexing or pointer-walking to offset n or beyond — or to a negative offset before the block — is out-of-bounds access and undefined behavior. The classic trigger is an off-by-one error: allocating room for a string of length len but forgetting the extra byte for the null terminator, so writing the terminating 0 lands one byte past the end. Another is copying more data into a block than it can hold, for example reading user input into a fixed-size heap buffer without checking the length. Because the bytes just past your block often hold the allocator's metadata for the next block, an overflow frequently corrupts that bookkeeping, and the program crashes later inside malloc or free, far from the line that actually overflowed.

This is one of the oldest and most exploited classes of security vulnerability. By overflowing a heap buffer in a controlled way, an attacker can overwrite a neighboring object — including, in the worst cases, function pointers or allocator metadata — and steer the program to run code of their choosing. The defenses are bounds discipline (always allocate sizeof for the data plus any terminator, never write more than the size you asked for) and tooling: AddressSanitizer places guard regions around allocations and reports the exact out-of-bounds access, and Valgrind catches many overruns too.

char *s = malloc(5); /* room for 5 bytes: indices 0..4 */ strcpy(s, "hello"); /* 'h','e','l','l','o','\0' = 6 bytes -> overflow! */ /* Correct: malloc(strlen("hello") + 1) leaves room for the null terminator */

A 5-byte block cannot hold a 5-character string plus its null terminator; the sixth byte overflows.

The crash often happens later, inside malloc or free, because the overflow corrupted the next block's header — the visible symptom is far from the real bug.

Also called
out-of-bounds heap accessheap overrun堆積越界存取