(not recommended due to lack of alignment)
updated to support alignment for cross-platform compatibility. speed untested
simple arena allocator in C99 with allocation alignment using alignof()
macro
[Inspired by Untangling Lifetimes: The Arena Allocator]
- Functions take
rkp_arena
references as arguments int rkp_arena_init(rkp_arena *arena)
initializes an arena, typically stack-allocated as shown in the example below. Data pages come frommalloc
void *rkp_arena_alloc(rkp_arena *arena, size_t size, size_t alignment)
is used likemalloc
void *rkp_arena_zalloc(rkp_arena *arena, size_t size, size_t alignment)
is used likemalloc
, but zeroes usingmemset
void *rkp_arena_grow_alloc(void *ptr, size_t old_size, size_t new_size, rkp_arena *arena)
can grow allocations and copy contents, somewhat likerealloc
but only supporting increases in sizechar *rkp_arena_new_str(char *str, rkp_arena *arena)
is likestrcpy
but allocates the new null-terminated string within the specified arenaint rkp_arena_reset(rkp_arena *arena)
will free all pages, and initialize a new page using the last page size.
exit()
is called ifmalloc()
fails
#include <stdio.h>
#include <inttypes.h>
#include <stdalign.h>
#include "rkp_arena.h"
#define BIGNUM 20000
int main(void) {
rkp_arena p;
rkp_arena_init(&p);
uint64_t **arr = rkp_arena_alloc(&p, BIGNUM * sizeof(uint64_t*), alignof(uint64_t *));
for(uint64_t i = 0; i < BIGNUM; i++) {
arr[i] = rkp_arena_alloc(&p, BIGNUM * sizeof(uint64_t), alignof(uint64_t));
for(uint64_t j = 0; j < BIGNUM; j++) {
arr[i][j] = i * j;
}
}
rkp_arena_print_info(&p);
rkp_arena_term(&p);
return 0;
}
#define MEMORY_HOG_FACTOR 8
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
#define DEF_BLOCK_SIZE 4096
is the first page size upon initialization usinginitArena()
. Default value4096
rkp_arena_get_bytes_used
,rkp_arena_get_bytes_allocd
, andrkp_arena_print_info
functions can be used to retrieve or print usage information at runtime