1
1
Fork
You've already forked arena.h
0
An arena allocator
  • C 100%
Adwaith-Rajesh 030136ecc9
[docs] README
added docs on using custom alignment
added docs on using the malloc backend
2026年02月17日 23:21:25 +05:30
.gitignore [docs] README 2026年02月17日 23:15:39 +05:30
arena.h [docs] add the stats flag 2026年02月17日 23:11:47 +05:30
LICENSE [LICENSE] + docs 2026年02月17日 22:45:28 +05:30
README.md [docs] README 2026年02月17日 23:21:25 +05:30

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_SIZE will fail and return NULL.
  • Metadata allocation: Chunk metadata is always allocated using malloc, regardless of the backend setting.

New features will be added based on my needs :)


Bye.....