typestar

An arena allocator in C

One big block, a bump pointer, and a single free at the end.

#include <stdlib.h>

typedef struct {
    unsigned char *base;
    size_t used;
    size_t cap;
} Arena;

int arena_init(Arena *a, size_t cap) {
    a->base = malloc(cap);
    a->used = 0;
    a->cap = (a->base == NULL) ? 0 : cap;
    return a->base != NULL;
}

void *arena_alloc(Arena *a, size_t n) {
    size_t aligned = (a->used + 15u) & ~(size_t) 15u;
    if (aligned + n > a->cap) {
        return NULL;
    }
    a->used = aligned + n;
    return a->base + aligned;
}

void arena_free(Arena *a) {
    free(a->base);
    a->base = NULL;
    a->used = 0;
    a->cap = 0;
}

How it works

  1. Allocation is a pointer bump, so it is very fast.
  2. Nothing is freed individually; the whole arena goes at once.
  3. Alignment is handled by rounding the offset up.

Keywords and builtins used here

The run, in numbers

Lines
30
Characters to type
504
Tokens
179
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 107 seconds.

Type this snippet

Step 3 of 4 in Ownership & mistakes, step 17 of 25 in Pointers & memory.

← Previous Next →