An arena allocator
|
Adwaith-Rajesh
030136ecc9
added docs on using custom alignment added docs on using the malloc backend |
||
|---|---|---|
| .gitignore | [docs] README | |
| arena.h | [docs] add the stats flag | |
| LICENSE | [LICENSE] + docs | |
| README.md | [docs] README | |
arena.h
An allocator for just my needs
Example
#define ARENA_ENABLE_STATS 1
#define ARENA_IMPLEMENTATION
#include "arena.h"
#include <stdio.h>#include <string.h>#include <stdint.h>
int main(void) {
Arena a = arena_init();
// Basic allocation
char *msg = arena_alloc(&a, 16);
strcpy(msg, "Hello");
/// Reallocate
msg = arena_realloc(&a, msg, 16, 64);
strcat(msg, ", Arena!");
// Another normal allocation
char *suffix = arena_alloc(&a, 16);
strcpy(suffix, " OK");
strcat(msg, suffix);
printf("Message: %s\n", msg);
// Show arena stats
/*
You can disable stats by not defining ARENA_ENABLE_STATS
*/
printf("\n--- Arena stats ---\n");
printf("n_mallocs: %ld\n", a.n_mallocs);
printf("n_mmaps: %ld\n", a.n_mmaps);
printf("n_chunks: %ld\n", a.n_chunks);
printf("total_size: %ld\n", a.total_size);
printf("total_committed: %ld\n", a.total_committed);
// Destroy arena
arena_destroy(&a);
return 0;
}
Using Custom Alignment
#define ARENA_IMPLEMENTATION
#include "arena.h"
int main(void) {
Arena a = arena_init();
// Allocate with custom alignment (e.g., 16-byte alignment)
void *aligned_ptr = arena_alloc_aligned(&a, 64, 16);
// Use aligned_ptr...
arena_destroy(&a);
return 0;
}
Using Malloc Backend
#define ARENA_BACKEND ARENA_BACKEND_MALLOC
#define ARENA_ENABLE_STATS 1
#define ARENA_IMPLEMENTATION
#include "arena.h"
int main(void) {
Arena a = arena_init();
// Allocations will use malloc backend
void *ptr = arena_alloc(&a, 100);
// Check malloc stats
printf("Mallocs: %ld\n", a.n_mallocs);
arena_destroy(&a);
return 0;
}
Limitations
- No reset function: Currently not implemented. Will be added when needed.
- No individual free: Individual memory blocks cannot be freed. All memory is freed when the arena is destroyed.
- Size limit: Allocations larger than
DEFAULT_CHUNK_SIZEwill fail and returnNULL. - Metadata allocation: Chunk metadata is always allocated using
malloc, regardless of the backend setting.
New features will be added based on my needs :)