Skip to main content

Lesson 9 of 26 · 12 min read

Free-space management and heap allocators

See how malloc(), free(), chunk headers, coalescing, placement heuristics, segregated lists, and buddy allocators battle external fragmentation.

Four free-space allocator actions: Chunk header, Split on alloc, Coalesce free, and Buddy / Slab.
Heap allocators embed headers behind returned pointers, split free regions on request, and coalesce holes when freed.
Course syllabus · lesson 9 of 26
In this lesson

The allocator behind malloc faces the same shape of problem as a kernel placing variable-size segments. It receives a request for contiguous storage and searches a collection of holes left by earlier frees. Sixteen free bytes here and sixteen there cannot satisfy a request for 24 contiguous bytes. That gap between total free capacity and the size of a feasible request is external fragmentation. The reverse kind, internal fragmentation, is unused space inside a block granted to a caller, for example after rounding its capacity up for alignment.

Follow a single arena managed in user space. Each block has an address and a span measured in bytes. The arena supplies storage for the allocator's bookkeeping as well as the application's payloads. The model omits concurrency and assumes the arena's start and length are aligned.

Heap arena showing an allocated block with size/magic header beside two adjacent free chunks (10B and 20B) that coalesce into a single 30B free chunk, plus placement heuristics below.
Open full-size diagram
Allocators store chunk metadata in an embedded header just behind the returned pointer, split large holes on malloc(), and coalesce neighbors on free().

Split and coalesce free space

Block A free 48 B, Block B free 48 B, Block C in use, Free list A–B: 96 BBlock Afree 48 BBlock Bfree 48 BBlock Cin useFree listA–B: 96 B

Step 1 of 3

Find a free span

The allocator has one contiguous 96-byte span across A and B. Block C is occupied. Sizes in this sketch include any allocator overhead.

Account for the header and the payload

When a caller asks for 20 bytes, the allocator needs room for the payload, alignment padding, and metadata. Assume 16-byte alignment and a target on which the following two-field structure occupies 16 bytes. Store the total span in bytes, including the header. On this target the payload pointer then lies 16 bytes after the block start, so it retains the alignment of the block.

Code exampleC
#include <stddef.h>
#include <stdint.h>

typedef struct {
    size_t span;
    uint64_t canary;
} header_t;

/* Precondition: payload is the exact pointer to a live arena allocation. */
static header_t *block_header(void *payload) {
    return (header_t *)((unsigned char *)payload - sizeof(header_t));
}

A request for 20 bytes uses a span of round_up(16 + 20, 16) = 48 bytes. It leaves 12 bytes of alignment padding after the requested payload. On free(payload), the allocator recovers the header and its full span, which lets it return the entire chunk to the free structure. The original request size and the allocation span serve different purposes. A real implementation might record one or both depending on its bookkeeping and diagnostic needs. It must check that the addition and rounding fit in size_t before choosing a chunk.

The canary is a reserved marker with a known value set when the allocator installs the header, for example h->canary = UINT64_C(0xC0FFEE1234AB5678). When releasing a block, compare the field with that value and reject a mismatch before reading the span into the free list. Check that the span is aligned, at least the minimum chunk size, and within the remaining arena extent before using it to compute an endpoint. Its coverage is limited. A small overflow may land entirely in padding. An overwritten size might leave the marker unchanged. Passing an arbitrary pointer to this function can already make the header read invalid. The caller's obligation is still to supply the exact start pointer of a live allocation. The teaching structure illustrates metadata layout and a sanity check, without implying that any particular C library stores these fields.

Store free records inside the arena

Once a chunk is free, the allocator can overwrite its bytes with a record describing the hole. In this model the record starts at the block boundary and contains a total span and a link. A singly linked list needs a head pointer outside the arena and one such record in every hole. The live allocation header and the free record occupy the same starting bytes at different times.

Code exampleC
typedef struct free_chunk {
    size_t span;
    struct free_chunk *next;
} free_chunk_t;

A simple allocator keeps the free list in increasing address order. It can scan to find the first fitting chunk or to insert a freed block before the first free record with a larger address. The order identifies the nearest free neighbor on each side, while arithmetic determines whether they are physically adjacent. Records and addresses here refer to offsets in the same arena. A production implementation can use arena-relative offsets for ordering, keeping comparisons within the same allocation.

The list representation imposes a minimum useful chunk size. Suppose the allocator enforces a 32-byte minimum for both allocated and free blocks. That fits the free record and, when allocated, leaves at least 16 bytes of payload after the header. If an 80-byte hole serves the request with a calculated 48-byte span, the remaining 32 bytes can carry their own free record. If a 64-byte hole serves the same request, the 16-byte remainder is below the minimum. Give the entire 64 bytes to the allocation and store span = 64. Returning 48 bytes on free would lose track of the rest of the chunk.

Split on allocation and coalesce at both boundaries

Given a hole at offset H with span S, a low-end split for a chunk of span N places its new header at H and the remainder at H + N. The intervals [H, H + N) and [H + N, H + S) partition the original hole. The allocator updates the free list to point to the remainder, then returns a payload pointer at H + sizeof(header_t). It absorbs a subminimum remainder into the allocation, so that no untracked pieces are left behind.

On free, locate the consecutive free-list entries surrounding the returned interval. The left record may be absent at the head of the list and the right record may be absent at the tail. Let the returned block start at B with span N.

  1. The left neighbor with start L and span S_left touches the returned block if L + S_left == B. Merge by extending its span to S_left + N. Use L as the start of the combined interval.
  2. Check the right neighbor against the updated interval. If the combined start plus span equals the right start, extend the interval by the right span and unlink that free record.
  3. The surviving record belongs at the start of the final interval. Its next link skips any record absorbed by a merge. A freed block with neither neighbor touching inserts a new record at its own start.

One insertion can therefore remove a neighboring record on each side. In a fully coalesced list, no two consecutive records describe touching intervals. If their endpoints cross, the model's invariant is already broken, for example by an invalid free or corrupt size. Allocators can trade more metadata for less searching. A boundary tag stores enough information at a block boundary to identify the previous physical block without scanning the list. Unlinking a free neighbor is direct if it also has a back link.

Compare placement on the same request

Imagine holes of 64, 128, and 80 bytes in increasing address order. The request needs a 48-byte span and the minimum remainder is 32 bytes.

  • First fit chooses the 64-byte hole and absorbs 16 bytes. It can stop after checking the first record. Repeated allocation near the head can leave small holes that lengthen later searches.
  • Best fit also chooses 64 here. An unsorted list generally requires finding the smallest acceptable hole with a full scan. Choosing the smallest hole does not guarantee the least internal waste. The 80-byte hole would have left a reusable 32-byte remainder for this request.
  • Worst fit chooses 128 and leaves 80 bytes. It tries to keep remainders useful, while consuming the largest hole that a bigger request might have needed.
  • Next fit resumes searching from the previous search position. If its next candidate is the 80-byte hole, it chooses that one and leaves 32 bytes. The cursor allows searches to spread out, and it needs maintenance when chunks merge or move between lists.

Policy outcomes depend on the allocation and free sequence. A segregated allocator uses separate lists for size classes to avoid repeatedly scanning unrelated holes. An object cache can arrange a region into equal-size slots and use a bitmap or free list to allocate them. That makes repeated allocations of the same type cheap. Space can still sit idle in a partially used region when demand shifts to another class.

Derive the buddy address from its offset

A binary buddy allocator starts with an aligned region of power-of-two size. It rounds the full request to an available power of two and repeatedly splits a larger free block into halves. Each order has a free list for a fixed size. Two blocks of size S can merge only if they are the two halves of the same 2 * S parent and both are currently free at that order.

For an arena-relative block offset B and size S, find the other half with BuddyOffset = B ^ S. Because S is a power of two, the exclusive-or flips one bit. Alignment already zeros the lower bits. The flipped bit distinguishes the left half from the right half of the parent. Use the offset relative to the buddy arena so that a physical or virtual base does not accidentally shift the pairing scheme.

For example, a 1 KiB arena can split into two 512-byte halves and then split the lower half into 256-byte blocks. The block at offset 0x100 has size 0x100, so its buddy is at 0x100 ^ 0x100 = 0x000. Once both halves are free, their parent at offset zero can itself merge with the 512-byte block at offset 0x200 if that block is free. Rounding a required span of 257 bytes to 512 consumes 255 bytes beyond the required span. Fast partner discovery comes with that rounding cost, and even adjacent same-size holes may be unable to merge when they belong to different parents.

Track bytes as the arena changes. At any point, the sum of the free spans and the allocated spans should equal the arena's original capacity. Header bytes and padding already belong to their blocks, so adding them again would double count them. A complementary check is to walk physical blocks in address order and verify that each starts where the previous one ends. The free-list walk checks which of those blocks can satisfy future requests. Those walks can reveal different errors. For example, forgetting to link a legal split remainder leaves the physical partition intact but makes some of its capacity unreachable through the free list.

Worked trace of a split and a two-sided merge

The arena begins with a free interval [0x1000, 0x1100) of 256 bytes. Use a 16-byte header, 16-byte alignment, a 32-byte minimum, and low-end splitting.

  1. Allocate A with 20 payload bytes. Its span is 0x30, the header starts at 0x1000, and the returned pointer is 0x1010. The free interval starts at 0x1030.
  2. Allocate B with 32 payload bytes. Its span is also 0x30, its pointer is 0x1040, and the remainder starts at 0x1060. The remainder has span 0xA0.
  3. Free A. Header recovery finds 0x1000. The free intervals are [0x1000, 0x1030) and [0x1060, 0x1100), separated by B. Their combined size is 208 bytes and their largest interval is only 160 bytes.
  4. Free B. Its recovered header starts at 0x1030. The left interval ends there, so merge to [0x1000, 0x1060). The new end is the start of the right interval. Merge again, leaving one 256-byte hole and one free record.

Change one input. Before either free, change B's request to 180 payload bytes. From 0x1030 the available span is 208 bytes. The header and payload require 196 bytes, which rounds to 208 bytes. B consumes the entire remainder and the free list is empty until a block is released.

Next, see how equal-sized frames change the problem in paging and page tables.

Before you move on

Try it in your workspace

Trace a 4 KiB heap arena through two allocations and one free() that merges with an adjacent free chunk. Compare best-fit, worst-fit, first-fit, and next-fit on external fragmentation.

Keep a short note of what you tried, what passed, and what you still need to check.

Your practice record

0 of 3 checked.

Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.