Memory Management & Allocators

🧠 Memory Management & Custom Allocators in Odin

Odin rejects hidden global memory managers. Instead of relying on a hidden malloc or runtime garbage collector, Odin passes memory allocators explicitly through the implicit context.allocator parameter.


🏛️ 1. Allocator Types in the Standard Library

Allocator Package Characteristics Best Used For
Heap Allocator context.default_allocator General-purpose OS heap wrapper (HeapAlloc / mmap) Persistent startup data, large buffers
Arena Allocator core:mem/virtual / core:mem Linear bump allocator; allocations advance pointer Frame/level lifetimes; instant bulk free
Stack / Scratchpad context.temp_allocator Circular ring buffer per frame High-frequency temporary calculations
Pool Allocator core:mem Fixed-size chunk slots; O(1) allocate/free Projectiles, particles, entity nodes
Tracking Allocator core:mem Records allocation addresses, sizes, and file locations Debug leak detection & memory profiling

🏗️ 2. The Custom Arena Allocator Pattern

In game systems, allocating 10,000 small structs individually causes memory fragmentation and cache misses. An Arena Allocator reserves a contiguous virtual memory block and bumps an internal offset pointer:

package main

import "core:fmt"
import "core:mem"

Game_Arena :: struct {
    arena:     mem.Arena,
    allocator: mem.Allocator,
}

init_game_arena :: proc(size: int) -> Game_Arena {
    buf := make([]u8, size, context.default_allocator)
    ga: Game_Arena
    mem.arena_init(&ga.arena, buf)
    ga.allocator = mem.arena_allocator(&ga.arena)
    return ga
}

main :: proc() {
    arena := init_game_arena(16 * mem.MEGABYTE)
    
    // Divert execution context to our arena
    context.allocator = arena.allocator
    
    // All allocations now pull contiguously from the arena
    entity_names := make([]string, 1024)
    entity_positions := make([][3]f32, 1024)
    
    // Free every single allocation in 1 CPU cycle
    mem.arena_free_all(&arena.arena)
}