Arena Allocator (C)
Topics: bump allocator, alignment, memory management
Problem
Implement a bump (arena) allocator over a fixed, caller-provided buffer — allocate by advancing
an offset, free everything at once. No malloc, no per-object free. It's the fast, scoped
allocation strategy used by compilers, game frames, and request handlers.
typedef struct { unsigned char *buf; size_t cap; size_t off; } Arena;
void arena_init(Arena *a, void *buf, size_t cap);
void *arena_alloc(Arena *a, size_t size, size_t align); // aligned; NULL if no room
void arena_reset(Arena *a); // free everything
size_t arena_used(const Arena *a);
arena_alloc rounds the current offset up to align (a power of two), returns that pointer,
and advances the offset by size. Returns NULL if it won't fit.
arena_reset sets the offset back to 0 (bulk free).
Key concepts
- Align up:
aligned = (off + (align-1)) & ~(align-1) for power-of-two align.
- Overflow-safe bounds check: test
size > cap - aligned (after aligned <= cap) rather than
aligned + size > cap, which can overflow.
- Bulk free: the whole point — drop everything in O(1) by resetting the offset; no individual
frees, no fragmentation.
Run
cc -std=c11 -O2 -Wall tests.c -o /tmp/arena && /tmp/arena
Sign in to submit your solution.