Lesson 5 of 5
Mini Project Part 6 - Arena Allocator
Build a simple **arena allocator** (also called a bump allocator) - a block of heap memory from which sub-allocations are served one after another without individual `free` calls. The entire arena is freed at once. This pattern is used in game engines, compilers, and high-performance servers where many short-lived allocations are made and then all discarded together.
Arena Allocator - Implementation & Usage
Arena Allocator - Implementation & Usage
/* arena.h - simple arena allocator */
#ifndef ARENA_H
#define ARENA_H
#include <stddef.h>
typedef struct {
char *base; /* start of the allocated block */
size_t capacity; /* total bytes in the arena */
size_t used; /* bytes allocated so far */
} Arena;
/* Create an arena of 'capacity' bytes (one malloc internally) */
int arena_init(Arena *a, size_t capacity);
/* Allocate 'size' bytes from the arena (no individual free) */
void *arena_alloc(Arena *a, size_t size);
/* Reset: all memory reclaimed, no individual free needed */
void arena_reset(Arena *a);
/* Destroy: release the underlying block */
void arena_destroy(Arena *a);
#endif
/* arena.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "arena.h"
/* Align to 8 bytes (portable for any fundamental type) */
static size_t align8(size_t n) {
return (n + 7) & ~(size_t)7;
}
int arena_init(Arena *a, size_t capacity) {
a->base = malloc(capacity);
if (a->base == NULL) return -1;
a->capacity = capacity;
a->used = 0;
return 0;
}
void *arena_alloc(Arena *a, size_t size) {
size_t aligned = align8(size);
if (a->used + aligned > a->capacity) {
fprintf(stderr, "arena: out of space (%zu + %zu > %zu)
",
a->used, aligned, a->capacity);
return NULL;
}
void *ptr = a->base + a->used;
a->used += aligned;
return ptr;
}
void arena_reset(Arena *a) {
a->used = 0; /* "free" everything cheaply - just move the cursor */
}
void arena_destroy(Arena *a) {
free(a->base);
a->base = NULL;
a->capacity = a->used = 0;
}
/* main.c - using the arena */
/*
#include <stdio.h>
#include <string.h>
#include "arena.h"
typedef struct { int id; char name[32]; float score; } Student;
int main(void) {
Arena arena;
if (arena_init(&arena, 4096) != 0) return 1; // 4 KB
// Allocate 10 Students from the arena
Student *students = arena_alloc(&arena, 10 * sizeof(Student));
if (!students) { arena_destroy(&arena); return 1; }
for (int i = 0; i < 10; i++) {
students[i].id = i + 1;
students[i].score = (float)(90 - i * 3);
snprintf(students[i].name, sizeof(students[i].name),
"Student_%02d", i + 1);
}
// Allocate a temporary string from the same arena
char *label = arena_alloc(&arena, 64);
if (label) {
strncpy(label, "Top Performers", 63);
label[63] = '