This explains why and how to use an arena allocator in C to simplify lifetime management and speed up allocation-heavy code. It argues that repeated malloc/realloc/free is error-prone (forgotten frees lead to leaks), slow for many small allocations, and makes ownership unclear. The arena approach groups objects by lifetime (whole program, a task/frame, or a function), reserves one large block, hands out aligned slices by bumping a pointer, and then frees or resets the whole block at once. That eliminates per-object frees, reduces syscall overhead, and makes lifetime semantics explicit to callers.
Concrete implementation details are given: a struct arena holds data, size, and used; arena_create returns a struct with the arena and a success flag; ARENA_ALIGN is set to 8 and alignment is computed as (ARENA_ALIGN - (arena->used % ARENA_ALIGN)) % ARENA_ALIGN before each allocation. arena_alloc returns a pointer+success and increments used; arena_realloc allocates a new slice, memcpys MIN(old,new) bytes and requires the caller to pass old_size; arena_clear resets used to 0 and arena_free frees the block. The API style uses small return structs with success fields and requires callers to pass an arena explicitly (so allocation intent and lifetime are clear). The trade-offs are inability to free individual allocations and the need to track sizes for resizing.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.