On this page
  1. Arena Allocator Pattern
  2. Contents
  3. Linear Bump Arena (Aligned $O(1)$ Allocation & Bulk Free)

Arena Allocator Pattern

Prev: Hash Table from Scratch | Up: tutorials | Next: C Shared Library with Python ctypes
Rel: Dynamic Memory & Allocators, Memory Management Models
Ref: Wikipedia — Region-Based Memory Management
Tags: #public #prog #c #tutorials #memory #allocators


Contents


Linear Bump Arena (Aligned $O(1)$ Allocation & Bulk Free)

Instead of calling malloc/free for thousands of short-lived nodes (ASTs, HTTP requests, frame scratchpads), allocate from one contiguous buffer by bumping an aligned offset, then release everything at once with arena_reset() or arena_destroy():

#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    unsigned char *buf;
    size_t         cap;
    size_t         offset;
} Arena;

static Arena arena_create(size_t cap) {
    return (Arena){ .buf = malloc(cap), .cap = cap, .offset = 0 };
}

static void *arena_alloc(Arena *a, size_t size, size_t align) {
    size_t aligned = (a->offset + (align - 1)) & ~(align - 1);
    if (!a->buf || aligned + size > a->cap) return NULL;
    void *ptr = a->buf + aligned;
    a->offset = aligned + size;
    return ptr;
}

static void arena_reset(Arena *a) { a->offset = 0; }
static void arena_destroy(Arena *a) { free(a->buf); a->buf = NULL; a->cap = a->offset = 0; }

int main(void) {
    Arena a = arena_create(4096);
    int *nums = arena_alloc(&a, 4 * sizeof(int), _Alignof(int));
    if (!nums) return 1;
    nums[0] = 42;
    printf("nums[0]=%d used=%zu bytes\n", nums[0], a.offset);
    arena_reset(&a);
    arena_destroy(&a);
    return 0;
}

Linked from

Related notes