Lesson 2 of 9 · 27m
Allocators, Ownership, and Memory Lifetimes
Choose allocators intentionally, transfer ownership explicitly, and use Zig's allocator-parameter convention to keep memory behavior testable and local.
Most memory disasters are not caused by a missing free. They are caused by two reasonable engineers holding different theories about who owns a buffer and how long it lives. Zig makes that theory part of the interface. Functions that need allocation accept an allocator; callers choose the allocation strategy; ownership transfer is something you write down in names, documentation, and tests.
The allocator is a dependency
Treat std.mem.Allocator like a capability. If a function receives one, assume it may allocate. If it does not receive one, assume it should not allocate unless it owns a fixed internal buffer or receives preallocated memory:
fn normalizeName(allocator: std.mem.Allocator, name: []const u8) ![]u8 {
const out = try allocator.alloc(u8, name.len);
for (name, 0..) |c, i| out[i] = std.ascii.toLower(c);
return out;
}The caller owns out now because the function returns freshly allocated memory. A good name or doc comment should say so. Returning []u8 rather than []const u8 also matters: it signals mutable ownership rather than a borrowed view.
Use arenas for phase lifetimes
Not every allocation needs individual bookkeeping. Batch jobs, parsers, request handlers, and command execution often have a natural phase lifetime. An arena lets you allocate freely and release everything at once:
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const a = arena.allocator();
const config = try loadConfig(a);
const plan = try buildPlan(a, config);
try executePlan(plan);This is not laziness. It is an ownership model: everything in the phase dies when the phase dies. The failure mode is memory growth when the phase secretly becomes long-lived. A command invocation is fine; a network daemon loop iteration usually is not unless you reset or recreate the arena per request.
Fixed buffers expose hidden assumptions
std.heap.FixedBufferAllocator is unglamorous and incredibly useful. It gives you allocation ergonomics over memory you already own:
var storage: [16 * 1024]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&storage);
const a = fba.allocator();Use it for tests, constrained environments, and places where unbounded growth should be impossible. It turns a silent memory leak or runaway input into an explicit error.OutOfMemory. That failure is often more useful than success because it forces you to decide whether the input limit or the architecture is wrong.
Ownership vocabulary that survives teams
Use precise verbs in APIs:
copy caller keeps input; callee allocates a duplicate
take callee assumes ownership and will free or transfer it
borrow callee uses memory only during the call
init returns an object with owned resources
deinit releases resources owned by that objectA struct with resources should make cleanup impossible to ignore:
const Scratch = struct {
allocator: std.mem.Allocator,
bytes: []u8,
fn init(allocator: std.mem.Allocator, size: usize) !Scratch {
return .{ .allocator = allocator, .bytes = try allocator.alloc(u8, size) };
}
fn deinit(self: *Scratch) void {
self.allocator.free(self.bytes);
}
};Detect leaks where they happen
GeneralPurposeAllocator can report leaks at deinit in debug builds. Run tests with it, but read the result correctly: leaked memory is a symptom of ownership confusion, not a puzzle to silence with a last-minute free. If a cache, global registry, or thread owns the memory, model that explicitly.
Field notes
- Freeing memory does not invalidate existing slices by magic. Stale slices are still dangerous even when your bookkeeping looks correct.
allocator.resizemay fail or move depending on allocator implementation; never assume growth is free.- Do not store an allocator in every object by habit. Sometimes passing it to methods makes lifetimes clearer; sometimes storing it is the only sane design. Choose deliberately.
arena.deinit()invalidates everything allocated from the arena. Returning arena-backed strings past the phase boundary is a classic bug.- The page allocator is not a general-purpose high-performance allocator; use a real allocator for many small allocations.
- Zig slices carry a pointer and length, not ownership. Ownership is a social contract that must be expressed in API shape.
Was this lesson helpful?