Module 10 · Lesson 38 of 112

Fixed-size and buddy heaps

Implement fixed-size and buddy heaps, measure how each handles fragmented memory, and verify that freeing a buddy heap restores its full arena.

  • Beginner to advanced
  • 8 min read
  • 53 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, the module's Rust toolchain, and the linked-list heap allocator from the previous lesson

Your place in the module
By the end you can 4 objectives
  • Select a fixed-size class from a request's size and alignment
  • Implement fixed-size allocation and deallocation using one free list per class
  • Split and coalesce buddy blocks using byte offsets and orders
  • Compare allocation failures, free-space fragmentation, and rounding waste on a repeatable trace
Video coming soonFixed-size and buddy heaps
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The linked-list heap allocator
  • Each header records the full block span, including the header itself.
  • First fit stops at the first usable block, while best fit scans for the smallest usable block.
  • An aligned payload can have its header immediately before it, with a representable free prefix retained.
01

Fixed-size pools for small requests

4 min read

The last lesson used a linked list. Now you build fixed-size block pools and a byte-granularity buddy allocator, and measure their fragmentation against the linked list.

A memory allocator can have enough free bytes in total and still fail a request for one contiguous block. Linux exposes this problem for physical pages through /proc/buddyinfo, which counts free blocks by order. A count of free blocks in the smaller orders tells you little about whether a block exists in a larger order. The kernel heap you build here has the same contiguity constraint at the byte level. proc_buddyinfo(5): free physical blocks by order

Follow the fixed-size-block design from the Blog OS allocator chapter, with a lab-specific class table of 64, 128, 256, 512, and 1024 bytes. Each has its own list head. Give each block alignment equal to its class size. Select the smallest class that covers both layout.size() and layout.align(). For example, a request for 48 bytes aligned to 128 bytes uses the 128-byte list. Choosing by size alone would permit a pointer that violates the requested alignment.

Allocate from a size classRead layoutsize andalignmentSelectclasssmallestclasscoveringbothInspectlist headPop freeblockExit from step 3: list emptyAllocate class layoutRead layoutsize andalignmentSelectclasssmallestclasscoveringbothInspectlist headPop freeblockExit from step 3: list emptyAllocate class layout
A class hit pops one block, while an empty class obtains a class-sized block from the fallback

On a class hit, read the first free block's next pointer and update the head. Return the block's address. The block already has the required size and alignment, so there is no search through the other free blocks. Store the next pointer inside the free block itself. At initialization, check that every class can hold a free-list node and meet its alignment. On allocation, read the link before handing the bytes to the caller. On free, write a fresh link before publishing the block as the new head. Keep the same synchronization around the heads and the fallback state as around your existing allocator state.

Start with empty lists and use the coalescing linked-list allocator as the fallback. When a selected list is empty, ask the fallback for a block with the class's size and alignment. Even if the caller needs only 48 bytes, a block acquired for the 64-byte class must have 64 bytes reserved for it. Otherwise a later 64-byte request could overwrite a neighboring allocation. A request beyond the class table goes directly to the fallback with its original layout. If the fallback cannot satisfy the request, report allocation failure using the existing interface.

On deallocation, repeat the class calculation with the original layout. Push a class block onto that list. Return a request beyond the class table directly to the fallback using the matching layout. This works because each supported class request always receives a block obtained for that class, including on a miss. Changing the miss path to allocate only the original layout would invalidate that rule.

Repeated requests in a class reuse complete blocks, which avoids cutting new holes in the fallback for every small request. There are two costs. A 65-byte allocation in a 128-byte block leaves 63 bytes unused inside the live block. Also, a free block cached in one list stays reserved for that class. The fallback cannot coalesce it with adjacent ranges, even if the other class lists are empty. Freeing every allocation may leave most of the heap cached in small blocks. A list hit is constant time. A miss can still require a fallback search.

02

A buddy heap that splits and coalesces

2 min read

Reuse the frame buddy arithmetic from M10-S04A4 with byte offsets. For this heap, take a single power-of-two arena and align its base to its full size. Use a minimum block size of 64 bytes in the lab. With a 4096-byte arena, order zero contains 64-byte blocks, order one contains 128-byte blocks, and order six contains the entire arena. In general, block_size = min_block << order. The full-size base alignment ensures that every block is aligned to its own size. Start with one free block at the highest order and empty lists at every lower order.

For allocation, take the maximum of the requested size, requested alignment, and minimum block size. Round up to the next power of two using checked arithmetic. If the result overflows or exceeds the arena, report failure. Convert the rounded size to a target order and look for a free block at that order or the first higher order with a free block. Remove one block. While it is larger than needed, split it into equal halves, put the upper half on the list for the new order, and continue with the lower half. When the order matches, return the retained half. If all eligible orders are empty, the request fails even when the smaller orders have free blocks.

Two levels of buddy splitting256-byte blockLower 128 bytesLower 64 bytesreturn to callerUpper 64 bytesinsert at order zeroUpper 128 bytesinsert at order one256-byte blockLower 128 bytesLower 64 bytesreturn to callerUpper 64 bytesinsert at order zeroUpper 128 bytesinsert at order one
Halving a block produces two siblings at the next lower order

On free, recover the initial order from the original layout. Subtract the arena base from the block address to get a byte offset. At the current order, compute buddy_offset = offset ^ block_size. The XOR flips the bit that distinguishes the two halves of their parent. For example, a 128-byte block at offset 256 has its buddy at offset 384. If both blocks are free, the merged 256-byte block starts at offset 256. Although blocks at offsets 128 and 256 are adjacent, they belong to different parents and cannot merge.

Before merging, look for the computed buddy on the current order's free list. Its presence confirms that the entire sibling is free at that order. If you find it, unlink it, keep the lower offset, advance one order, and repeat. Otherwise insert the current block at its current order and stop. At the maximum order, insert the whole arena and stop before computing a buddy outside it. Insert the resulting block once. Publishing a child and then publishing its merged parent would make the same bytes available to two allocations.

With simple singly linked lists, the search for a specific buddy can scan a list even though XOR finds its offset immediately. The number of split or merge levels is bounded by the number of orders. Eager merging recovers larger blocks when both siblings become free. A live block can prevent merging through several orders, and power-of-two rounding wastes space inside live blocks. Both effects depend on the workload.

03

Measure what the heap can reuse

3 min read
Going deeperExplore the mechanism

At a snapshot, record total free bytes and the largest contiguous block the allocator can actually grant at a stated alignment. In the linked-list heap, measure the largest request that fits a free range after alignment and any minimum-fragment rules. In the buddy heap, a free order is usable for a request that rounds to that order or below. For the fixed-size heap, count free bytes in both the fallback and the cached classes. Include cache blocks when finding the largest grant only if the request would select their class. A fallback range that appears large enough by length alone can still fail the layout check.

The difference between free capacity and the size of a single usable allocation reflects . For a quick comparison, report 1 - largest_grant / total_free when total free is positive, using the same alignment and request path for every run. Label this a snapshot indicator. To show how the fixed-size cache affects it, report the available count in each class and the fallback's largest grant separately. Record actual layout-specific failures too. A single ratio cannot show that the 64-byte class has blocks ready while a 128-byte request fails. Measure separately by summing reserved_bytes - requested_bytes over live allocations. Include any space the linked-list allocator actually consumes for each allocation in its reserved count.

Heap snapshot measurementsMeasureWhat to countFree capacityTotal freebytesAll freeblocksContiguouscapacityLargest grantOne alignedrequestLive allocationwasteInternalfragmentationReservedminusrequested
Measure reusable free space and unused bytes inside live allocations separately

For a small benchmark, run the three allocator implementations directly on fresh, equally sized, equally aligned arenas under the Ubuntu host test harness. Keep the trace, pointer slots, and measurement storage outside the arenas. Use a deterministic mixed trace with valid layouts, for example sizes 48, 72, 120, and 200 bytes at alignment 8, plus 48 bytes at alignment 128. Fill a batch, free alternating slots, and refill those slots first with the same layouts. Then free alternating slots again and refill with different layouts. Same-layout churn exercises cache hits. Changing layouts exposes whether free capacity is usable across classes and whether alignment leaves holes in the linked-list heap. Keep the operation sequence the same after a failure by marking the slot empty and skipping its matching free. Report failures alongside timing because a failed allocation can execute less work than a successful one.

In a separate pressure phase, record free bytes and attempt a valid larger layout while some small allocations are still live. For the buddy heap, allocate a row of minimum-size blocks from a fresh arena and free one sibling from every pair. A request for twice the minimum size must fail when every pair still has a live sibling and the row covers the arena. Free the rest and inspect every order. The highest-order list should contain one block at offset zero and every lower list should be empty. Repeat with a different free order, then request the full arena and check that it succeeds. These checks distinguish actual coalescing from a free-byte counter that happens to reach the right total.

Take snapshots outside the timed runs. Time repeated batches in a release build with a monotonic clock and report elapsed time per attempted operation, counting the attempts and successes. Ubuntu provides CLOCK_MONOTONIC for elapsed-time measurement through clock_gettime. Use several runs and report the median for each trace. Record the arena size and the number of operations so the comparison can be reproduced. clock_gettime(3): monotonic time and clock resolution

In “Using the heap and its collections”, you will use the initialized heap from Rust code that creates and grows collections. The layouts those collections request determine which allocation path runs.

Key takeaways

  • A cached fixed-size block can be allocated or freed by updating one list head
  • Cached blocks remain available to their own size class and can reduce the space available to the fallback allocator
  • A buddy heap merges free siblings of the same order and can recover the full arena after all allocations are freed
  • Total free bytes alone cannot predict whether a particular size and alignment request will succeed
Reflect
  1. Explain to a colleague, in two sentences: select a fixed-size class from a request's size and alignment
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close