Memory
Arena and pool allocators. An arena allocates variable-sized blocks from one buffer; a pool reuses fixed-sized chunks.
Usage#
Include lfmemory.h and create the allocator handle. The caller owns the handle. Initialize it before allocating, and free its storage when finished.
ArenaAllocator arena = {0};
if (arena_init(&arena, 1024) == 0) {
int *value = arena_malloc(&arena, sizeof(*value));
if (value != NULL) {
*value = 42;
}
arena_free(&arena);
}
Arena allocations start zeroed and are aligned to LF_DEFAULT_ALIGNMENT. Do not call free on individual allocations. Clearing or freeing the arena invalidates all of them.
Use a pool when each allocation needs the same amount of space. Return individual chunks with pool_free so they can be reused.
PoolAllocator pool = {0};
if (pool_init(&pool, 1024, 32, LF_DEFAULT_ALIGNMENT) == 0) {
void *chunk = pool_alloc(&pool);
pool_free(&pool, chunk);
pool_destroy(&pool);
}
Do not initialize a live allocator again before releasing its storage. Zero-initialize handles if you need cleanup after a failed initialization.
Structs#
ArenaAllocator#
The handle may live on the stack or the heap. owns_buf is 1 when arena_init malloc'd the slab and 0 when arena_init_buf borrowed it. Callers may read owns_buf. The other fields are allocator state. Do not write them.
typedef struct {
unsigned char* buf;
size_t buf_sz;
size_t offset_cur;
size_t offset_prev;
size_t save_stack[LF_ARENA_MAX_SAVE_POINTS];
size_t save_count;
int owns_buf;
} ArenaAllocator;PoolAllocator#
free_count is the number of chunks still available. Read it with pool_count_available. Do not write the fields.
typedef struct {
unsigned char *buf;
size_t buf_sz;
size_t chunk_size;
size_t aligned_start;
size_t free_count;
void *free_head;
} PoolAllocator;Functions#
arena_init#
Allocates a slab of buf_sz bytes and initializes the handle. Returns 0 on success. Returns -1 if allocator is NULL, and writes nothing. If malloc fails, sets buf to NULL and owns_buf to 0, leaves the other fields unchanged, and returns -1. A live handle loses its previous slab pointer. The slab from a successful init is owned by the arena.
int arena_init(ArenaAllocator *allocator, size_t buf_sz);arena_init_buf#
Binds the arena to caller-owned storage. The arena does not take ownership: arena_free detaches without freeing storage, and arena_resize_buf is rejected. storage must be non-NULL and n must be non-zero. Returned pointers are aligned to LF_DEFAULT_ALIGNMENT from the storage address. Returns 0 on success. Returns -1 and leaves the handle unchanged if allocator is NULL, storage is NULL, or n is 0.
int arena_init_buf(ArenaAllocator *allocator, void *storage, size_t n);arena_free#
If the arena owns its slab, frees it. Always resets the handle. Does not free the allocator struct. arena_free(NULL) does nothing.
void arena_free(ArenaAllocator *allocator);arena_clear#
Sets both offsets and save_count to 0. Does not free or wipe the buffer. Every previous allocation and save point is invalid. Requires a non-NULL initialized handle.
void arena_clear(ArenaAllocator *allocator);arena_malloc#
Allocates and zeros size bytes. The returned address is aligned to LF_DEFAULT_ALIGNMENT. Alignment padding is taken from the buffer, so a request can fail while size itself is smaller than the bytes left. Returns NULL if allocator is NULL, the slab is missing, or the aligned block does not fit. Failure does not move the bump.
A size of 0 does not reserve a byte after alignment. The next allocation starts at that same address. arena_copy of length 0 avoids the alias by reserving one byte.
void *arena_malloc(ArenaAllocator* allocator, size_t size);arena_copy#
Copies n bytes from src into a fresh block aligned to LF_DEFAULT_ALIGNMENT. The block comes from arena_malloc, which zeroes it; the copy then overwrites the first n bytes. Returns NULL if allocator is NULL, if src is NULL and n > 0, or if the arena cannot hold the block. A failed call does not move the bump.
n == 0 returns a non-NULL pointer and copies nothing. src may be NULL in that case and is not read. Because arena_malloc(0) does not reserve a byte, a zero-length copy allocates one byte so the next block cannot alias this pointer. That byte is not part of the copy. Do not pass the result to free. Clearing, restoring past the block, or freeing the arena releases it.
void *arena_copy(ArenaAllocator *allocator, const void *src, size_t n);lfstr_copy_arena#
Declared in lfstring.h and defined in src/string.c. Copies an LfStr into the arena: s.n bytes, then one trailing NUL that is not counted in out->n. This is not lfstr_substr_arena. That function measures a C string with strlen and cannot see past the first NUL. lfstr_copy_arena copies s.n bytes even when a NUL sits in the middle.
Returns 0 on success. *out views those n bytes. A zero-length input (n == 0) stores a non-NULL empty C string (one NUL byte) and does not read s.p. Returns -1 on failure and leaves *out unchanged. *out is written only after the copy succeeds. Failure includes a NULL allocator, a NULL out, s.n > 0 with s.p == NULL, s.n == SIZE_MAX (s.n + 1 would overflow; nothing is allocated), and an arena that cannot hold the block. An arena_malloc failure does not move the bump, so an earlier copy stays readable. Do not pass the result to free. A NULL allocator does not fall back to the heap.
int lfstr_copy_arena(ArenaAllocator *allocator, LfStr s, LfStr *out);arena_resize_buf#
Grows or shrinks the owned slab to new_sz. Returns 0 on success. Returns -1 if allocator is NULL, the arena does not own the slab, new_sz is 0, new_sz is less than offset_cur, or realloc fails. Failure leaves the slab and the offsets unchanged. Success may move the slab, and every pointer into the old slab is then invalid. The bytes added by a grow are not zeroed. Use arena_free to release the slab.
int arena_resize_buf(ArenaAllocator *allocator, const size_t new_sz);arena_resize#
Resizes one block. Pass that block's real size as old_sz. This function does not record sizes.
A NULL mem or a zero old_sz allocates a new block, the same way arena_malloc does. The previous pointer, if any, is not reclaimed.
If mem is the latest block and new_sz fits at its current start, the block is resized in place and the same pointer is returned. Growth zeroes the new tail. A shrink rewinds the bump. Bytes past the new size are no longer part of the block and are not wiped. new_sz of 0 on that latest block rewinds the bump to the block's start and returns the same pointer, so the next allocation can alias it.
If mem lies in the slab but is not the latest block, a new aligned block is allocated and the first min(old_sz, new_sz) bytes are copied. Bytes past that prefix are zero. The old block stays allocated until clear, restore, or free. Use the returned pointer. A new_sz of 0 on this path does not reserve a byte, same as arena_malloc(0).
Returns NULL if allocator is NULL, the slab is missing, mem is outside the slab, or the new size does not fit. Failure leaves the offsets and the old bytes unchanged.
void *arena_resize(ArenaAllocator *allocator, void *mem, size_t old_sz, size_t new_sz);arena_save#
Pushes offset_cur onto the save stack. Requires a non-NULL initialized handle. Returns 0 on success. Returns -1 and pushes nothing if save_count is already LF_ARENA_MAX_SAVE_POINTS.
int arena_save(ArenaAllocator *allocator);arena_restore#
Pops the most recent save and sets both offset_cur and offset_prev to that offset. Does nothing if the stack is empty. Memory past the restored offset is invalid. A block allocated before the save keeps the bytes that still sit below that offset. An in-place grow of the latest block past the save point is rewound with the bump. Requires a non-NULL initialized handle.
void arena_restore(ArenaAllocator *allocator);pool_init#
Allocates a slab and splits it into fixed chunks. Free chunks store a next pointer in their first bytes. Later allocation and return do not call the system allocator.
chunk_sz is rounded up to a multiple of chunk_align. The rounded size must be at least sizeof(void *) and must fit in the aligned slab. chunk_align must be a non-zero power of two. Returns 0 on success. Returns -1 if allocator is NULL, buf_sz is 0, chunk_sz is 0, chunk_align is not a usable power of two, malloc fails, or the slab cannot hold one aligned chunk. Failure leaves the handle unchanged.
int pool_init(PoolAllocator *allocator, size_t buf_sz, size_t chunk_sz, size_t chunk_align);pool_alloc#
Returns one zeroed chunk of the rounded chunk size, or NULL if allocator is NULL or the free list is empty.
void *pool_alloc(PoolAllocator *allocator);pool_free#
Pushes one chunk back onto the free list. A NULL allocator, a pool with no slab, a NULL ptr, a pointer that is not the start of a chunk, and a chunk already on the free list are ignored. The free count is unchanged in those cases.
void pool_free(PoolAllocator *allocator, void *ptr);pool_free_all#
Rebuilds the free list from every chunk. Pointers obtained before this call are invalid. A NULL allocator, a missing slab, or a zero chunk size does nothing.
void pool_free_all(PoolAllocator *allocator);pool_destroy#
Frees the slab and zeroes the handle. Does not free the allocator struct. pool_destroy(NULL) does nothing. A second destroy on a handle this function already zeroed frees nothing.
void pool_destroy(PoolAllocator *allocator);Macros#
pool_count_available#
The number of chunks still on the free list. x must be a non-NULL pool.
#define pool_count_available(x) ((x)->free_count)LF_ARENA_MAX_SAVE_POINTS#
Maximum number of nested arena_save points. Override it to the same value in the library and in callers. It is an array inside the handle, so a mismatch changes the layout. The default is 32.
#ifndef LF_ARENA_MAX_SAVE_POINTS
#define LF_ARENA_MAX_SAVE_POINTS 32
#endifLF_DEFAULT_ALIGNMENT#
Alignment of arena blocks, and the alignment most callers pass as chunk_align. The default is twice the pointer size, which is 16 when a pointer is 8 bytes. It must be a non-zero power of two. Override it when building the library. Callers must see the same value.
#ifndef LF_DEFAULT_ALIGNMENT
#define LF_DEFAULT_ALIGNMENT (2*sizeof(void*))
#endif