CC Explainer
C · 6 · Advanced / Job-Ready35 / 35 · 100%

Writing a Small Allocator

Bump and pool allocators — a classic systems interview exercise.

Examples: arena, alignment, free list

shortcuts: ← prev · → next · M mark
1

Bump / Arena Allocator

Allocation is a pointer increment; you free everything at once.

Example
example
typedef struct { char *base, *cur, *end; } Arena;

void *arena_alloc(Arena *a, size_t n, size_t align) {
    uintptr_t p = (uintptr_t)a->cur;
    p = (p + align - 1) & ~(uintptr_t)(align - 1);   // round up
    if ((char*)p + n > a->end) return NULL;
    a->cur = (char*)p + n;
    return (void*)p;
}

void arena_reset(Arena *a) { a->cur = a->base; }
2

Pool Allocator

Fixed-size blocks and a free list — O(1) alloc and free.

Example
example
typedef struct Block { struct Block *next; } Block;

void *pool_alloc(Block **free_list) {
    Block *b = *free_list;
    if (b) *free_list = b->next;
    return b;
}

void pool_free(Block **free_list, void *p) {
    Block *b = p; b->next = *free_list; *free_list = b;
}
10•20•30•40•→ NULL
free list threaded through unused blocks
3

Alignment Rules

Every returned pointer must be suitably aligned for any type.

Example
example
#include <stdalign.h>
size_t align = alignof(max_align_t);   // usually 16 on x86-64
WATCH OUT
Misaligned access is undefined behavior in C and a hard fault on some architectures.
4

Why Bother

Custom allocators trade generality for speed.

Complexity
malloc/freegeneralthread-safe, fragmentation handling
arena allocO(1)no per-object free
arena resetO(1)frees everything
pool alloc/freeO(1)fixed size only