Project
Basic C memory arena implementation
Single-header arena allocator in C99/C11 with optional aligned allocations and expansion.
RoleSystems Programming
Date26-07-2025
Tech
C99C11MemoryAllocator
Highlights
- Single-header (stb-style) arena allocator in C99/C11
- Optional aligned allocations plus expansion support
- Unit tests and examples included
Overview
va_c_arena is a stb-style, single-header arena allocator. Include va_arena.h, define VA_ARENA_IMPLEMENTATION once, and you get fast bump-pointer allocations with optional alignment and expansion.
Features
- C99 core; C11+ adds aligned allocation helpers.
- Single-header API; drop-in and cross-platform (uses malloc/realloc/free only).
- Arena expansion via
arena_expandwhen you need more space. - Optional aligned allocations (
arena_alloc_aligned) for stricter alignment needs. - Unit tests and examples included.
Usage sketch
- Create an arena with a starting size (e.g., 4 KB).
- Allocate with
arena_alloc(...); optionally usearena_alloc_aligned(...)on C11+. - Optionally call
arena_expand(...)to grow the arena (note: existing pointers may become invalid after expansion). - Destroy the arena to free memory.
Example (Aligned Allocation, C11+)
#include <stdio.h>
#include <stdalign.h>
#define VA_ARENA_IMPLEMENTATION
#include "va_arena.h"
typedef struct {
VA_ALIGNAS(32) int id;
VA_ALIGNAS(32) double position[3];
VA_ALIGNAS(32) char name[32];
} Entity;
int main(void) {
Arena *arena = arena_create(4096);
Entity *entities = (Entity *)arena_alloc_aligned(arena, sizeof(Entity) * 10, 32);
if (!entities) {
fprintf(stderr, "Failed to allocate aligned entities\n");
arena_destroy(&arena);
return 1;
}
// Use entities...
arena_destroy(&arena);
return 0;
}
Notes
- Not thread-safe; add your own synchronization if sharing across threads.
- Expansion can move the underlying block; do not use old pointers after
arena_expand. - Aligned helpers require C11 or newer.