Memory

Kaigen doesn't use the C standard library, so there's no malloc and no free. Every system owns its memory through an allocator, and most memory is allocated once and lives for as long as the thing that owns it.

This sounds strict, but in practice it makes memory easier: you rarely free anything, leaks are hard to write, and every allocator shows up in the engine's memory stats.

Allocators

An Allocator is a small interface that every system takes. You allocate through it with macros, and everything comes back zeroed.

Allocating
Thing *t = ALLOC(allocator, Thing);
Thing *things = ALLOC_ARRAY(allocator, Thing, count);

There are two kinds you'll create yourself:

Both reserve address space up front and only commit memory as you use it, so reserving 64 MB costs nothing until you touch it.

An arena for your game
ArenaAllocator *arena = arena_create(MB(64), MB(1));
Allocator alloc = make_arena_allocator(arena);
Level *level = ALLOC(&alloc, Level);

Your application state itself is allocated by the engine, zeroed, from the size app_state_size returns.

Scratch memory

For temporary work (formatting a string, a buffer for one function) every lane has its own scratch arena. You take a slice of it and give it back:

Temporary memory
tctx_temp_allocator_scope(ta, NULL) {
  String path = str_format(&ta.allocator, "levels/%.hzt", fmt_cstr(name));
  load_level(path);
}

Scratch arenas also reset at the end of every frame, so nothing allocated there survives to the next one.

Use scratch memory instead of arrays on the stack. Threads on the web have small stacks, and a char buffer[4096] that works on your desktop will crash a browser.

Worth knowing

The full API is in hz/src/lib/memory.h, allocator_arena.h and allocator_tlsf.h.