single-header arena allocator in C99
[Inspired by Untangling Lifetimes: The Arena Allocator]
- Functions take
Arena
references as arguments int initArena(*arena)
initializes an arena, typically stack-allocated as shown in the example belowvoid *palloc(*arena, size)
is used likemalloc
void *pzalloc(*arena, size)
is used likemalloc
, but zeroes usingmemset
void *pGrowAlloc(*arena, *ptr, old_size, new_size)
can grow allocations and copy contents, somewhat likerealloc
but only supporting increases in sizechar *pNewStr(*arena, *str)
is likestrcpy
but allocates the new null-terminated string in the arenaint resetArena(*arena)
will free all pages, and initialize a new page using the last page size
#include "arena.h"
#include <inttypes.h>
#define BIGNUM 20000
int main(void) {
Arena p;
initArena(&p);
uint64_t **arr = palloc(&p, BIGNUM * sizeof(uint64_t*));
for(uint64_t i = 0; i < BIGNUM; i++) {
arr[i] = palloc(&p, BIGNUM * sizeof(uint64_t));
for(uint64_t j = 0; j < BIGNUM; j++) {
arr[i][j] = i * j;
}
}
termArena(&p);
return 0;
}
MEMORY_HOG_FACTOR
will be multiplied by requested allocation size to determine new page size, in case the current page is not large enough. Larger values result in fewer overall calls tomalloc
. Default value8
DEFAULT_PAGE_SIZE
is the first page size upon initialization usinginitArena()
. Default value4096
int setAllocator(fn_ptr)
allows overridingmalloc
if desired. Replacement must be of the formvoid *(*alloc_fn)(size_t)
(likemalloc
)getBytesUsed(*arena)
,getBytesAllocd(*arena)
, andprintArenaInfo(*arena)
can be used to retrieve or print usage information at runtime