pointers-memory · advanced · ~40 min
Bump-pointer allocation + alignment math.
Implement a bump arena:
typedef struct { char *base; size_t size, used; } arena_t;
arena_t *arena_create(size_t size);
void *arena_alloc(arena_t *a, size_t n, size_t align);
void arena_reset(arena_t *a);
void arena_destroy(arena_t *a);
arena_alloc rounds the current used up to align, then returns the next n bytes. Returns NULL on overflow. align is a power of 2.
Arenas are the secret weapon of every fast C codebase — Chromium's Skia, Postgres's per-query allocator, Lua's parser. You allocate fast and free everything at once.
Sizes in bytes; alignment a power of 2.
Pointer or NULL.
No per-allocation metadata; no individual free.
#include <stddef.h>
#ifndef ARENA_T_DEFINED
#define ARENA_T_DEFINED
typedef struct { char *base; size_t size, used; } arena_t;
#endif
arena_t *arena_create(size_t size);
void *arena_alloc(arena_t *a, size_t n, size_t align);
void arena_reset(arena_t *a);
void arena_destroy(arena_t *a);
Aligning with (used + align - 1) & ~(align - 1) but forgetting that ~(align-1) has the wrong type if align is int; not checking for arithmetic overflow before comparing to size.
n == 0 returns a pointer (current bump location) but uses no bytes. Allocation that would push past size returns NULL.
O(1) per alloc. O(1) reset.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.