--- name: c-arena description: Arena allocator pattern — bump allocation with chaining, scratch blocks, push macros, position-based deallocation. Use when: managing memory in C, building allocators, performance-critical allocation. license: MIT --- # Arena Allocators Arena allocators (bump allocators) provide fast, simple memory management with no individual deallocation overhead. --- ## Core Concept Allocate by bumping a pointer. Deallocate by resetting the pointer. No fragmentation, no per-allocation overhead. ### Trade-offs | Pros | Cons | | ------------------------------- | ------------------------------ | | O(1) allocation | No individual deallocation | | No fragmentation | Memory held until arena reset | | Cache-friendly (contiguous) | Must track lifetimes manually | | No allocation failures at setup | Not for variable-lifetime data | --- ## Arena Structure ```c #define ARENA_HEADER_SIZE 128 typedef U32 ArenaFlags; enum { ArenaFlag_NoChain = (1 << 0), ArenaFlag_LargePages = (1 << 1), }; typedef struct Arena Arena; struct Arena { Arena *prev; // Previous block in chain Arena *current; // Current block (for chained arenas) ArenaFlags flags; // Configuration flags U64 cmt_size; // Commit granularity U64 res_size; // Reserved size U64 base_pos; // Base position (for chaining) U64 pos; // Current position U64 cmt; // Committed bytes U64 res; // Reserved bytes }; ``` ### Memory Layout ``` +------------------+ | Arena header | <- ARENA_HEADER_SIZE bytes +------------------+ | | | Available space | <- pos grows downward | | +------------------+ ``` --- ## Core Operations ### Allocation ```c internal void * arena_push(Arena *arena, U64 size, U64 align, B32 zero) { Arena *current = arena->current; // Align position U64 pos_aligned = AlignPow2(current->pos, align); U64 pos_new = pos_aligned + size; // Chain new block if needed if (pos_new > current->res && !(arena->flags & ArenaFlag_NoChain)) { // Allocate new block and chain it Arena *new_block = arena_alloc(.reserve_size = current->res_size, .commit_size = current->cmt_size); new_block->base_pos = current->base_pos + current->res; current = new_block; arena->current = current; pos_aligned = AlignPow2(current->pos, align); pos_new = pos_aligned + size; } // Commit more pages if needed if (pos_new > current->cmt) { U64 commit_size = AlignPow2(pos_new - current->cmt, current->cmt_size); os_commit((U8 *)current + current->cmt, commit_size); current->cmt += commit_size; } // Bump pointer and return void *result = (U8 *)current + pos_aligned; current->pos = pos_new; if (zero) { MemoryZero(result, size); } return result; } ``` ### Position-Based Deallocation ```c internal U64 arena_pos(Arena *arena) { Arena *current = arena->current; return current->base_pos + current->pos; } internal void arena_pop_to(Arena *arena, U64 pos) { // Find the block containing this position Arena *current = arena->current; while (current->base_pos > pos && current->prev != arena) { current = current->prev; } // Set position current->pos = pos - current->base_pos; arena->current = current; } ``` --- ## Push Macros Type-safe allocation macros: ```c #define push_array_aligned(arena, T, count, align) \ (T *)arena_push((arena), sizeof(T) * (count), (align), 1) #define push_array_no_zero_aligned(arena, T, count, align) \ (T *)arena_push((arena), sizeof(T) * (count), (align), 0) #define push_array(arena, T, count) \ push_array_aligned(arena, T, count, Max(8, alignof(T))) #define push_array_no_zero(arena, T, count) \ push_array_no_zero_aligned(arena, T, count, Max(8, alignof(T))) #define push_struct(arena, T) \ push_array(arena, T, 1) #define push_struct_no_zero(arena, T) \ push_array_no_zero(arena, T, 1) ``` ### Usage ```c Arena *arena = arena_alloc(.reserve_size = MB(64)); // Single struct (zeroed) MyStruct *s = push_struct(arena, MyStruct); // Array (zeroed) int *values = push_array(arena, int, 100); // Array (not zeroed, faster) float *buffer = push_array_no_zero(arena, float, 1024); ``` --- ## Scratch Blocks (Temporary Memory) Temporary allocations that are automatically freed when the scope ends. ### Implementation ```c typedef struct Temp Temp; struct Temp { Arena *arena; U64 pos; }; internal Temp temp_begin(Arena *arena) { Temp temp; temp.arena = arena; temp.pos = arena_pos(arena); return temp; } internal void temp_end(Temp temp) { arena_pop_to(temp.arena, temp.pos); } ``` ### Thread-Local Scratch Pool ```c #define SCRATCH_POOL_COUNT 2 thread_static Arena *scratch_pool[SCRATCH_POOL_COUNT]; internal Arena * tctx_get_scratch(Arena **conflicts, U64 count) { for (U64 i = 0; i < SCRATCH_POOL_COUNT; i++) { Arena *candidate = scratch_pool[i]; B32 is_conflict = 0; for (U64 j = 0; j < count; j++) { if (candidate == conflicts[j]) { is_conflict = 1; break; } } if (!is_conflict) { return candidate; } } return 0; } #define scratch_begin(conflicts, count) temp_begin(tctx_get_scratch((conflicts), (count))) #define scratch_end(scratch) temp_end(scratch) ``` ### Usage ```c internal String8 build_path(Arena *arena, String8 dir, String8 file) { // Get scratch arena that doesn't conflict with output arena Temp scratch = scratch_begin(&arena, 1); // Temporary allocations String8List list = {0}; str8_list_push(scratch.arena, &list, dir); str8_list_push(scratch.arena, &list, str8_lit("/")); str8_list_push(scratch.arena, &list, file); // Final allocation into output arena String8 result = str8_list_join(arena, &list); // Free all scratch allocations scratch_end(scratch); return result; } ``` --- --- ## ASAN Integration Poison memory that shouldn't be accessed: ```c internal void * arena_push(Arena *arena, U64 size, U64 align, B32 zero) { // ... allocation ... // Poison the gap from old pos to aligned pos if (pos_aligned > current->pos) { AsanPoisonMemoryRegion((U8 *)current + current->pos, pos_aligned - current->pos); } // Unpoison the new allocation AsanUnpoisonMemoryRegion(result, size); return result; } ``` --- ## When to Use | Use Arena When | Don't Use Arena When | | ------------------------------ | --------------------------------- | | All data has same lifetime | Individual deallocation needed | | Building up temporary results | Long-lived with varying lifetimes | | Processing frames in game loop | Need to free memory incrementally | | Parsing/compiling | Memory is scarce | | Batch operations | | --- ## Quick Reference ```c // Create Arena *arena = arena_alloc(.reserve_size = MB(64)); // Allocate MyStruct *s = push_struct(arena, MyStruct); int *arr = push_array(arena, int, count); // Save position for later reset U64 pos = arena_pos(arena); // ... more allocations ... arena_pop_to(arena, pos); // Temporary scope Temp scratch = scratch_begin(0, 0); // ... use scratch.arena ... scratch_end(scratch); // Destroy arena_release(arena); ```