Skip to content
systemcoding.dev
Performance

Write a Buddy Allocator in C for Page-Sized Blocks

Build a buddy allocator in C that splits and merges power-of-two runs of 4 KiB pages with an XOR buddy lookup, per-order free lists and a worked trace.

7 min read
Summarize in AI
Flat illustration of heap memory as allocated and free blocks, with the C, Linux and Rust logos.

Every general-purpose allocator has to answer the same awkward question: when a block is freed, is its neighbor free too, and can the two be merged back into something larger? A buddy allocator answers it with arithmetic instead of a search. Blocks come only in power-of-two sizes, every block of size 2^k sits at an offset that is a multiple of 2^k, and the neighbor you could merge with is found by flipping one bit of the address. This post builds that allocator in C for a pool of 4 KiB pages, with an intrusive free list per order, splitting on allocation and coalescing on free. It is the same scheme the Linux page allocator uses for physical memory, and it is the right starting point before you read the memory allocator comparisons for performance work that treat allocators as black boxes.

The code targets C11 and glibc 2.41 on a 64-bit Linux system, and uses only aligned_alloc from the standard library to get a page-aligned arena.

The invariant that makes the buddy lookup work

Number the pages of the pool from 0. An allocation of order k returns a run of 2^k consecutive pages whose first page index is a multiple of 2^k. That alignment rule is the whole trick. The two halves of an order k+1 block start at index i and i + 2^k, where i is a multiple of 2^(k+1). So the two halves differ in exactly bit k of their start index, and the buddy of a block of order k starting at index i is:

Text
buddy(i, k) = i XOR (1 << k)

The Linux kernel computes it the same way in __find_buddy_pfn() in mm/internal.h, applying the XOR to a page frame number. There is no table to search and no neighbor pointer to maintain. Given a block and its order, the buddy's start page is one instruction away, and what remains is to know whether that buddy is currently a free block of exactly the same order.

Data structures

Three pieces of state are enough. A set of free lists, one per order, holds the free blocks. The list node lives inside the free block itself, which is safe because a free block's memory is unused, and costs no extra memory. A small array free_order[] records, for the first page of every free block, the order of that block, and holds -1 for every page that is not the head of a free block. That array is what the merge step consults.

buddy.cc
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PAGE_SIZE 4096u
#define MAX_ORDER 4
#define NPAGES    (1u << MAX_ORDER)

struct node { struct node *next, *prev; };

static unsigned char *base;
static struct node head[MAX_ORDER + 1];
static int8_t free_order[NPAGES];

static void list_init(struct node *h) { h->next = h->prev = h; }

static void list_add(struct node *h, struct node *n) {
    n->next = h->next;
    n->prev = h;
    h->next->prev = n;
    h->next = n;
}

static void list_del(struct node *n) {
    n->prev->next = n->next;
    n->next->prev = n->prev;
}

static void *addr_of(unsigned idx) { return base + (size_t)idx * PAGE_SIZE; }
static unsigned idx_of(void *p) {
    return (unsigned)(((unsigned char *)p - base) / PAGE_SIZE);
}

static void insert_free(unsigned idx, int order) {
    free_order[idx] = (int8_t)order;
    list_add(&head[order], (struct node *)addr_of(idx));
}

static void remove_free(unsigned idx) {
    list_del((struct node *)addr_of(idx));
    free_order[idx] = -1;
}

MAX_ORDER is 4, so the pool holds 16 pages (64 KiB) and the largest block is the whole pool. The Linux kernel uses a larger maximum order (the constant is MAX_PAGE_ORDER in recent kernels), but the structure is identical. Each list is a circular doubly linked list with a sentinel in head[], so insertion and removal never branch on an empty list.

Initialize the pool

aligned_alloc needs the size to be a multiple of the alignment, which 16 * 4096 is. At the start the pool is one free block of the maximum order.

buddy.cc
static void buddy_init(void) {
    base = aligned_alloc(PAGE_SIZE, (size_t)NPAGES * PAGE_SIZE);
    if (!base) { perror("aligned_alloc"); exit(1); }
    memset(free_order, -1, sizeof free_order);
    for (int o = 0; o <= MAX_ORDER; o++) list_init(&head[o]);
    insert_free(0, MAX_ORDER);
}

Allocate by splitting

To serve a request of order k, scan upward from k for the smallest non-empty list. Take its first block. While the block is larger than requested, cut it in half: keep the lower half and put the upper half on the free list one order down. The upper half starts at idx + 2^(o-1) after the order is decremented, which is the buddy of the half you keep.

buddy.cc
static void *buddy_alloc(int order) {
    int o = order;
    while (o <= MAX_ORDER && head[o].next == &head[o]) o++;
    if (o > MAX_ORDER) return NULL;

    struct node *n = head[o].next;
    unsigned idx = idx_of(n);
    remove_free(idx);

    while (o > order) {
        o--;
        insert_free(idx + (1u << o), o);
    }
    return addr_of(idx);
}

Splitting is cheap because each split is one list insertion. A request for a single page from a pool that holds only the order 4 block performs four splits and leaves one free block of each smaller order behind. Those leftovers are what makes the next small allocation fast.

Free by merging

On free, the caller passes the order, as the kernel's __free_pages() also requires. The loop looks at the buddy. If the buddy is the head of a free block of exactly this order, remove it from its list, move the block start down to the lower of the two, raise the order by one and try again. When no merge is possible, or the order reaches the maximum, the block goes onto its list.

buddy.cc
static void buddy_free(void *p, int order) {
    unsigned idx = idx_of(p);
    while (order < MAX_ORDER) {
        unsigned buddy = idx ^ (1u << order);
        if (free_order[buddy] != order) break;
        remove_free(buddy);
        idx &= ~(1u << order);
        order++;
    }
    insert_free(idx, order);
}

The test free_order[buddy] != order covers two different reasons to stop. The buddy might be allocated, in which case its entry is -1. Or it might be free but split into smaller blocks, in which case its head entry holds a lower order, or the page is not a head and holds -1. In both cases the buddy cannot be merged whole.

Trace a small run

This driver prints the free lists after each phase. The dump function walks each circular list and prints the page index of every block.

buddy.cc
static void dump(void) {
    for (int o = 0; o <= MAX_ORDER; o++) {
        printf("order %d:", o);
        for (struct node *n = head[o].next; n != &head[o]; n = n->next)
            printf(" %u", idx_of(n));
        printf("\n");
    }
}

int main(void) {
    buddy_init();
    void *a = buddy_alloc(0);
    void *b = buddy_alloc(1);
    void *c = buddy_alloc(0);
    printf("a=%u b=%u c=%u\n", idx_of(a), idx_of(b), idx_of(c));
    dump();

    buddy_free(a, 0);
    buddy_free(c, 0);
    buddy_free(b, 1);
    printf("after freeing everything\n");
    dump();
    free(base);
    return 0;
}

Work through it by hand. The pool starts as one free block, order 4, at page 0. buddy_alloc(0) takes it and splits down: it frees page 8 as order 3, page 4 as order 2, page 2 as order 1 and page 1 as order 0, and returns page 0. buddy_alloc(1) finds the order 1 block at page 2 and returns it. buddy_alloc(0) takes the order 0 block at page 1. The free lists now hold only the order 2 block at page 4 and the order 3 block at page 8.

Freeing a finds its buddy, page 1, allocated, so page 0 goes back as an order 0 block. Freeing c (page 1) finds page 0 free at order 0, merges to an order 1 block at page 0, then checks the buddy at page 2, which is still allocated, and stops. Freeing b (page 2, order 1) finds its buddy at page 0 free at order 1, merges to order 2, finds page 4 free at order 2 and merges to order 3, finds page 8 free at order 3, and merges to the full order 4 block.

Text
a=0 b=2 c=1
order 0:
order 1:
order 2: 4
order 3: 8
order 4:
after freeing everything
order 0:
order 1:
order 2:
order 3:
order 4: 0

The pool is back to a single maximal block, which is the property that lets a buddy allocator recover from fragmentation as long as every neighbor is eventually freed.

What this version leaves out

The sketch is deliberately small, and a real page allocator adds several things. It is not thread safe, so a kernel puts a lock, or a per-CPU cache in front of it. The caller must remember the order, whereas a general malloc has to store it in a header. Memory is rounded up to a power of two, so a request for 5 pages consumes 8, and that wasted space is internal fragmentation. The kernel also groups free blocks by migrate type so that movable and unmovable pages do not mix, and it splits memory into zones. You can see the effect of all that on a running machine in /proc/buddyinfo, which prints the free block count per order for each zone, and the format is documented in the kernel's proc filesystem documentation.

For a user-space allocator, the buddy scheme is rarely the final answer, because power-of-two rounding wastes memory for general object sizes. It remains the right tool for page-granular pools, such as a DMA buffer arena, a GPU memory sub-allocator or the backing store beneath a slab allocator.

Also inKernels
Taggedcexpert
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.