# Memory

> Allocators instead of malloc, and a scratch arena per lane that resets every frame.

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:

- **Arenas** (`arena_create(reserve, commit)`) hand out memory by bumping a pointer. You don't free single allocations, you reset or destroy the whole arena. This is what you want almost always: a level, a system, a frame.
- **TLSF** (`tlsf_allocator_create(reserve, commit)`) is for the rare case where things come and go one at a time and need a real `ALLOC_FREE`.

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 `NULL` in `tctx_temp_allocator_scope(ta, NULL)` is the *conflict* arena. If you're filling an allocator that might itself be this lane's scratch arena, pass it there and you get the other one.
- `ALLOC` zeroes. The `_NO_ZERO` variants skip it when you're about to overwrite everything anyway.
- A pointer into a growable array moves when the array grows. Keep indices or handles, not pointers.

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