C / raylib
Advanced
C99 / C11
게임 프레임 단위를 위한 고성능 C 언어 선형 아레나 메모리 할당기(Arena Allocator)High-Performance C Linear Arena Memory Allocator for Per-Frame Lifetimes
malloc/free 반복으로 인한 힙 단편화와 시스템 콜 오버헤드를 줄이고, 프레임 종료 시 포인터 오프셋을 0으로 초기화해 일괄 해제하는 선형 메모리 아레나 구현입니다.A linear arena allocator in C that eliminates heap fragmentation and malloc/free overhead by advancing a single offset pointer and resetting it in O(1) at the end of each frame.
#C #Memory Management #Optimization #Low Level #Performance
핵심 개념매 프레임 임시 생성되는 수백 개의 적 총알, 파티클, UI 문자열 버퍼를 매번
malloc과 free로 처리하면 힙 단편화와 캐시 미스가 발생합니다. 연속된 단일 메모리 블록을 미리 예약하고 포인터 오프셋만 전진시키는 선형 아레나(Arena) 할당기를 사용하면, 할당은 포인터 덧셈 연산으로 끝나고 해제는 오프셋을 0으로 되돌리는 O(1) 연산으로 처리됩니다.Key ConceptAllocating and freeing hundreds of transient bullets, particles, or UI formatting buffers every frame via
malloc and free causes heap fragmentation and cache misses. By pre-allocating a contiguous memory block and advancing a single offset pointer in a linear Arena, allocation reduces to pointer addition and deallocation becomes an O(1) offset reset to zero.1. 메모리 정렬을 지원하는 아레나 구현1. Aligned Linear Arena Implementation in C
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
typedef struct {
uint8_t *buffer;
size_t capacity;
size_t offset;
} Arena;
Arena arena_create(size_t capacity) {
Arena a;
a.buffer = (uint8_t *)malloc(capacity);
assert(a.buffer != NULL);
a.capacity = capacity;
a.offset = 0;
return a;
}
// 8바이트 메모리 정렬(Alignment)을 보장하는 선형 할당
void *arena_alloc(Arena *a, size_t size) {
size_t aligned_offset = (a->offset + 7) & ~(size_t)7; // 8-byte align
if (aligned_offset + size > a->capacity) {
return NULL; // OOM (Out Of Memory)
}
void *ptr = &a->buffer[aligned_offset];
a->offset = aligned_offset + size;
return ptr;
}
// 프레임 종료 시 O(1) 전체 초기화
void arena_reset(Arena *a) {
a->offset = 0;
}
void arena_destroy(Arena *a) {
free(a->buffer);
a->buffer = NULL;
a->capacity = 0;
a->offset = 0;
}
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
typedef struct {
uint8_t *buffer;
size_t capacity;
size_t offset;
} Arena;
Arena arena_create(size_t capacity) {
Arena a;
a.buffer = (uint8_t *)malloc(capacity);
assert(a.buffer != NULL);
a.capacity = capacity;
a.offset = 0;
return a;
}
// Linear allocation with 8-byte memory alignment
void *arena_alloc(Arena *a, size_t size) {
size_t aligned_offset = (a->offset + 7) & ~(size_t)7; // 8-byte align
if (aligned_offset + size > a->capacity) {
return NULL; // OOM (Out Of Memory)
}
void *ptr = &a->buffer[aligned_offset];
a->offset = aligned_offset + size;
return ptr;
}
// O(1) bulk reset at the end of a frame
void arena_reset(Arena *a) {
a->offset = 0;
}
void arena_destroy(Arena *a) {
free(a->buffer);
a->buffer = NULL;
a->capacity = 0;
a->offset = 0;
}
2. 실무 적용 및 주의사항2. Practical Considerations and Caveats
- 수명 주기(Lifetime)별 아레나 분리: 아레나 할당기는 개별 포인터 단위의 부분 해제를 지원하지 않으므로, 프로그램 종료까지 유지되는 영구 에셋 아레나(
Permanent Arena), 스테이지 전환 시 비우는 레벨 아레나(Level Arena), 매 프레임 끝에서arena_reset을 호출하는 프레임 스크래치 아레나(Frame Arena)로 분리해 운용해야 합니다. - CPU 아키텍처별 정렬(Alignment) 요구사항: 64비트 포인터나
double타입은 8바이트 경계 정렬이 필요하며, SIMD(SSE/NEON) 벡터 연산용 배열을 할당할 때는(offset + 15) & ~(size_t)15와 같이 16바이트 이상으로 정렬 단위를 확장해야 정렬 예외(Bus Error)를 막을 수 있습니다. - 디버그 빌드에서 초기화 패턴 채우기:
arena_reset은 오프셋만 0으로 되돌릴 뿐 기존 메모리 내용을 지우지 않으므로, 이전 프레임의 포인터를 잘못 참조하는 댕글링 포인터 버그를 조기에 잡으려면 디버그 빌드에서 리셋 시memset(a->buffer, 0xDD, a->offset)으로 오염 패턴을 기록하는 것이 유용합니다.
- Partition Arenas by Lifetime: Because an arena does not free individual allocations, separate memory into distinct arenas by lifetime: a
Permanent Arenafor global assets, aLevel Arenacleared on stage transitions, and aFrame Arenareset every frame viaarena_reset. - Respect Architecture Alignment Requirements: 64-bit pointers and
doublevalues require 8-byte alignment, while SIMD (SSE/NEON) data buffers require 16-byte or 32-byte alignment ((offset + 15) & ~(size_t)15) to avoid unaligned access faults. - Poison Memory on Reset in Debug Builds: Because
arena_resetonly resetsoffsetto 0 without clearing memory, filling the used region with a poison byte (memset(a->buffer, 0xDD, a->offset)) in debug builds helps catch dangling pointers carried over from previous frames.
수명이 동일한 객체들을 선형 아레나에 묶어 관리하면 개별 메모리 해제 누수(Memory Leak) 가능성을 구조적으로 줄이고, 연속된 메모리 배치를 통해 CPU L1/L2 캐시 적중률을 높일 수 있습니다.
Grouping allocations with identical lifetimes into a linear arena prevents individual memory leaks and improves CPU cache locality by keeping per-frame data contiguous.