When a program needs space for data whose size is not known in advance, an allocator can manage memory without putting a huge array on the stack. An allocator is a data structure with a common interface for obtaining and releasing memory. Freeing a block tells the allocator it can reuse that memory. section 3.1.2
Stack memory is assigned to function calls, but it is limited; using too much can cause a crash or even corrupt data. Allocators typically manage heap memory, which a program can request from the operating system through system calls. Zig makes the allocator choice explicit, giving code control over where memory is allocated. section 3.1.2 section 3.6
Choose an allocator to fit the lifetime of the data:
- A general-purpose allocator suits allocations that need to be freed as the program goes. Match each allocation with a free. section 3.4.2
- An arena allocator suits many allocations that can share a lifetime. Clean up the arena to release them together. section 5.3.2 section 3.4.2
A Zig main function can receive std.process.Init, which supplies a general-purpose allocator and an allocator for data that lives until the process ends. The smaller std.process.Init.Minimal provides environment variables and command-line arguments instead. section 3.1.1
Cleaning up file contents
A file-printing loop can read each file with init.gpa, write its contents, and free the buffer. But if writing fails before the free, the buffer leaks. Put the free in a defer immediately after allocation: it runs when the loop scope exits, including on an error. The program then holds only one file’s contents at a time. section 3.4.2
for (args[1..]) |filepath| {
const text = try cwd.readFileAlloc(
init.gpa,
filepath,
io,
.unlimited,
);
defer init.gpa.free(text);
try stdout.writeAll(text);
}
The loop defers freeing each file buffer before attempting the write. section 3.4.2
Sharing a lifetime for strings
A recipe collection can put its recipe and ingredient strings in an arena, avoiding individual tracking when those strings can be freed together. Its AutoHashMapUnmanaged does not retain an allocator, so operations must receive one instead; this avoids storing the allocator multiple times. section 5.3.2



