Dynamic Memory Management

allocation metadata (the block header)

Here is a small puzzle. When you call free(p), you pass only the pointer — you never tell free how big the block was. Yet free has to know the size, so it can return the right amount of memory to the free list and check its neighbors for coalescing. How does it know? The answer is that the allocator quietly stored the size and other bookkeeping next to your block, in a small region called the block header (or metadata).

Precisely: when malloc gives you a pointer to your usable bytes, it has typically placed a few hidden bytes just before that pointer — the header — recording at least the block's size and whether it is free or in use, and often links for the free list. So the memory layout for one allocation looks like header, then the bytes you actually use. The pointer malloc returns points at your usable region, just past the header. When you call free(p), the allocator steps backward from p by the header size, reads the size and flags it finds there, and uses them to reclaim the block. This is why you must pass free exactly the pointer malloc returned: a pointer into the middle of your block would point at the wrong place, and the allocator would read garbage where it expects a header.

This metadata has two consequences worth remembering. First, it is overhead: every allocation costs a little extra memory for its header (and alignment padding), which is why making thousands of tiny separate allocations is wasteful compared to one big block or a memory pool. Second, the header sits in memory right next to your usable bytes, so a buffer overflow that writes past the end of your block can overwrite the header of the next block, corrupting the allocator. That is exactly why heap overflows so often crash later inside malloc or free rather than at the line that overflowed — the damage is to the bookkeeping, not to your own data.

Memory layout of one allocation: [ header: size + free/used flag ][ your usable bytes -> p points HERE ] free(p) steps back from p to read the header, then reclaims the block.

The size lives in a hidden header just before your pointer; that is how free knows how much to reclaim without being told.

The header explains why you must free the exact pointer malloc returned, why overflows corrupt the allocator, and why many tiny allocations waste memory in per-block overhead.

Also called
block headerallocation headerbookkeeping區塊標頭記帳資料