Arena allocation for frame-based tasks
What you'll learn: How to use a "scratchpad" memory strategy to handle temporary data in loops without causing memory leaks or fragmentation.
The problem with manual cleanup
In programs that run in a continuous loop—like game engines, web servers, or physics simulators—you often need temporary memory for a single "frame" of work. If you use malloc() and free() for every small string or temporary array, your code becomes cluttered with cleanup logic. Even worse, if you forget a single free(), your program will slowly consume all system memory until it crashes.
The "Notebook" analogy
Imagine you are a waiter taking orders. You could use a separate sticky note for every single item ordered, carefully throwing each one away as the food is delivered. This is slow and messy.
Instead, you use a spiral notebook. For each new table (a "frame"), you write down all their orders on one page. Once the table is served, you don't erase the lines one by one. You simply flip to a fresh page. At the end of the shift, you throw the whole notebook away. This is Arena Allocation.
How it works in code
An arena is just a large, pre-allocated block of memory. Instead of freeing individual objects, you simply reset a single pointer back to the start of the block when the frame is finished.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *buffer;
size_t capacity;
size_t offset;
} Arena;
// Grab a chunk of memory from the arena
void* arena_alloc(Arena *a, size_t size) {
if (a->offset + size <= a->capacity) {
void *ptr = &a->buffer[a->offset];
a->offset += size;
return ptr;
}
return NULL; // Out of memory
}
// The "Magic": Wipe everything at once
void arena_reset(Arena *a) {
a->offset = 0;
}
int main() {
Arena frame_arena = { .buffer = malloc(1024), .capacity = 1024, .offset = 0 };
while (1) { // Simulation loop
// 1. Allocate temporary "frame" data
int *coords = arena_alloc(&frame_arena, sizeof(int) * 3);
// 2. Perform work...
// 3. Instant cleanup for the next frame
arena_reset(&frame_arena);
}
free(frame_arena.buffer);
return 0;
}
Why this is powerful
Because you only call arena_reset, it is impossible to have a memory leak within your loop. It doesn't matter if you allocated one object or one thousand; resetting the offset to zero makes that memory "available" instantly. This is extremely fast and keeps your core logic clean.
Key takeaway
Arena allocation turns complex memory management into a simple "reset" button for repetitive tasks.