c / expert
Snippet
Arena Memory Allocation with Strict Pointer Alignment
An Arena Allocator manages linear bump allocation over a fixed byte buffer to avoid malloc overhead and fragmentation. High-performance systems require data memory addresses aligned to hardware boundaries (e.g. 4 or 8 bytes). Bitwise arithmetic `(current + (align - 1)) & ~(align - 1)` efficiently rounds up pointers to the next alignment boundary prior to advancing arena offset markers.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>#include <stdint.h>#include <stddef.h>typedef struct {uint8_t *buffer;size_t capacity;size_t offset;} Arena;void *arena_alloc(Arena *arena, size_t size, size_t alignment) {uintptr_t current_ptr = (uintptr_t)(arena->buffer + arena->offset);uintptr_t aligned_ptr = (current_ptr + (alignment - 1)) & ~(alignment - 1);size_t padding = aligned_ptr - current_ptr;if (arena->offset + padding + size > arena->capacity) return NULL;arena->offset += padding + size;return (void *)aligned_ptr;}int main(void) {uint8_t memory_pool[1024];Arena arena = { .buffer = memory_pool, .capacity = sizeof(memory_pool), .offset = 0 };double *val = (double *)arena_alloc(&arena, sizeof(double), _Alignof(double));if (val) {*val = 3.14159;printf("Allocated aligned double: %f at %p\n", *val, (void *)val);}return 0;}
Breakdown
1
uintptr_t current_ptr = (uintptr_t)(arena->buffer + arena->offset);
Converts current byte offset address into integer representation for bitwise math.
2
uintptr_t aligned_ptr = (current_ptr + (alignment - 1)) & ~(alignment - 1);
Applies bitwise AND mask to align address upwards to power-of-two alignment boundary.
3
*val = (double *)arena_alloc(&arena, sizeof(double), _Alignof(double));
Requests memory with alignment requirement supplied via C11 _Alignof operator.