Zig Choosing an Allocator
Zig’s standard library comes with several allocators, and that can feel like too much choice when all you want is some memory. Here’s the reassuring part: most programs need one or two of them, and because they all share the std.mem.Allocator calls from Zig Allocators, switching from one to another is usually a one-line change. This lesson walks through them from “use this by default” to “use this for special cases”, and ends with a short checklist.
Start here: init.gpa
Section titled “Start here: init.gpa”If your main takes init: std.process.Init, you already have a good general-purpose allocator: init.gpa. For most programs, that’s the answer.
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const names = try gpa.alloc([]const u8, 2); defer gpa.free(names); names[0] = "Ana"; names[1] = "Bo";
std.debug.print("{d} names, first is {s}\n", .{ names.len, names[0] });}Output:
2 names, first is AnaWhat’s behind init.gpa depends on the build mode. We checked this in the 0.17.1 source (lib/std/start.zig):
- In
debugandsafebuilds, it’s astd.heap.SafeAllocator. It checks your work: it reports memory you forgot to free, and it catches freeing the same memory twice. That’s what you want while writing and testing. - In
fastandsmallbuilds, it’s a faster allocator with no checks:std.heap.smp_allocatornormally, or C’smalloc(std.heap.c_allocator) if you link libc.
So you get checks while you develop and speed when you ship, without changing a line. Zig Build Modes covers the modes themselves.
SafeAllocator: the checking allocator, set up by hand
Section titled “SafeAllocator: the checking allocator, set up by hand”Sometimes you don’t have init, for example in a main with no parameters, or in a library’s own example program. Then you can make the same checking allocator yourself:
const std = @import("std");
pub fn main() !void { var safe: std.heap.SafeAllocator = .init(std.heap.page_allocator, .{}); defer { const leaks = safe.deinit(); std.debug.print("leaks: {d}\n", .{leaks}); } const gpa = safe.allocator();
const nums = try gpa.alloc(u32, 3); defer gpa.free(nums); @memset(nums, 1); std.debug.print("{any}\n", .{nums});}Output:
{ 1, 1, 1 }leaks: 0Three steps, and you’ll see this shape with every allocator that has its own state:
- Make the allocator’s state as a
var(heresafe), with.init(...).SafeAllocatortakes a backing allocator, the place it gets its big chunks of memory from, and options (.{}means the defaults). - Get the
std.mem.Allocatorinterface from it with.allocator(), and pass that around. - Clean up the state with
deinit()at the end. ForSafeAllocator,deinitreports any leaks and returns how many there were.
The defer that prints leaks: 0 runs last, after gpa.free(nums), because defers run in reverse order.
page_allocator: straight from the operating system
Section titled “page_allocator: straight from the operating system”std.heap.page_allocator asks the operating system for memory directly, every time. The OS hands out memory in whole pages, 4096 bytes on our machine:
const std = @import("std");
pub fn main() !void { const page = std.heap.page_allocator;
const one = try page.alloc(u8, 1); defer page.free(one); one[0] = 'x';
std.debug.print("got {d} byte, page size {d}\n", .{ one.len, std.heap.pageSize() });}Output:
got 1 byte, page size 4096You asked for 1 byte, and your slice has length 1, but behind the scenes a whole page was set aside, and each call is a trip to the operating system. That makes page_allocator a poor choice for lots of small things. Where it shines is as the backing allocator for another one, like SafeAllocator above or an arena below: those ask for a few big chunks and hand out small pieces themselves. It’s always there, needs no setup, and is safe to use from several threads.
ArenaAllocator: free everything at once
Section titled “ArenaAllocator: free everything at once”An arena hands out memory and never frees single items. Instead, you free everything at once with one deinit:
const std = @import("std");
pub fn main(init: std.process.Init) !void { var arena: std.heap.ArenaAllocator = .init(init.gpa); defer arena.deinit(); const a = arena.allocator();
const greeting = try a.print("Hello, {s}!", .{"arena"}); const nums = try a.alloc(u32, 3); @memset(nums, 7);
std.debug.print("{s} {any}\n", .{ greeting, nums });}Output:
Hello, arena! { 7, 7, 7 }No free for greeting or nums: arena.deinit() gives back both. This is great for short programs and for work that happens in rounds, like one web request or one game frame. It’s important enough to get its own lesson, Zig Arena Allocator, which also covers init.arena.
FixedBufferAllocator: memory from a buffer you own
Section titled “FixedBufferAllocator: memory from a buffer you own”std.heap.FixedBufferAllocator hands out memory from a byte array you give it. No operating system, no heap. When the buffer is full, it returns error.OutOfMemory:
const std = @import("std");
pub fn main() void { var buffer: [16]u8 = undefined; var fba: std.heap.FixedBufferAllocator = .init(&buffer); const a = fba.allocator();
const first = a.alloc(u8, 10) catch unreachable; std.debug.print("first: {d} bytes, used {d} of 16\n", .{ first.len, fba.end_index });
if (a.alloc(u8, 10)) |_| { std.debug.print("second worked\n", .{}); } else |err| { std.debug.print("second: {s}\n", .{@errorName(err)}); }
fba.reset(); std.debug.print("after reset: used {d}\n", .{fba.end_index});}Output:
first: 10 bytes, used 10 of 16second: OutOfMemoryafter reset: used 0buffer lives on the stack, so the whole thing needs no heap at all. The second request needs 10 more bytes, only 6 are left, so it fails with OutOfMemory. fba.reset() forgets every allocation and starts again from the beginning of the buffer.
Use it when you know the most memory you’ll ever need, for example on a small embedded device, in a function that must never touch the heap, or for scratch space in a hot loop. And it’s a handy way to test that your code handles error.OutOfMemory: give it a tiny buffer and watch.
BufferFirstAllocator: a buffer first, the heap if needed
Section titled “BufferFirstAllocator: a buffer first, the heap if needed”Often a small buffer is enough, but now and then you need more. std.heap.BufferFirstAllocator tries a buffer you give it first, and only goes to a fallback allocator when the buffer runs out:
const std = @import("std");
pub fn main(init: std.process.Init) !void { var buf: [64]u8 = undefined; var bfa: std.heap.BufferFirstAllocator = .init(&buf, init.gpa); const a = bfa.allocator();
const small = try a.alloc(u8, 32); defer a.free(small); const big = try a.alloc(u8, 1000); defer a.free(big);
std.debug.print("small came from the buffer: {}\n", .{bfa.fixed_buffer_allocator.ownsSlice(small)}); std.debug.print("big came from the buffer: {}\n", .{bfa.fixed_buffer_allocator.ownsSlice(big)});}Output:
small came from the buffer: truebig came from the buffer: falseThe 32 bytes fit in the 64-byte buffer. The 1000 bytes didn’t, so they came from init.gpa. Free both through a as usual: it knows which is which. In Zig 0.16 and earlier this was called StackFallbackAllocator, and it was set up differently; 0.17 renamed and simplified it.
The rest, briefly
Section titled “The rest, briefly”std.heap.smp_allocator: a fast general-purpose allocator forfastbuilds with several threads. It’s whatinit.gpabecomes in afastbuild without libc.std.heap.c_allocator: C’smallocandfree. Use it when you link libc anyway (zig run -lc main.zig); without-lcit’s a compile error.std.testing.allocator: only insidetestblocks. It’s a checking allocator that makes a test fail if it leaks. See Zig Testing Allocator.std.heap.MemoryPool(T): hands out many objects of one type, quickly. Worth a look when you make and free thousands of the same struct.
A short checklist
Section titled “A short checklist”The language reference’s guide to choosing an allocator has a flow chart (it still says DebugAllocator, which 0.17 replaced with SafeAllocator). Boiled down:
- Writing a library? Don’t pick. Take a
std.mem.Allocatorparameter and let the user decide. - Writing a test?
std.testing.allocator. - Know the most memory you’ll need?
FixedBufferAllocator(orBufferFirstAllocatorif you’re only usually under it). - Everything can be freed at the same moment (end of the program, end of a request)?
ArenaAllocator. - Anything else?
init.gpa. It checks your work indebugand goes fast infast.
Practice
Section titled “Practice”1. Count your leaks
Section titled “1. Count your leaks”Set up a SafeAllocator by hand in a main with no parameters, allocate 5 bytes and don’t free them, and make the program print leaks: 1 at the end. (You’ll also see the leak report above it; that’s expected.)
Hint: copy the SafeAllocator example and remove the defer gpa.free(...) line. You’ll need _ = bytes; so Zig doesn’t complain about an unused variable.
Show solution
const std = @import("std");
pub fn main() !void { var safe: std.heap.SafeAllocator = .init(std.heap.page_allocator, .{}); defer { const leaks = safe.deinit(); std.debug.print("leaks: {d}\n", .{leaks}); } const gpa = safe.allocator();
const bytes = try gpa.alloc(u8, 5); _ = bytes;}You’ll see something like:
error(SafeAllocator): leaked [addr: 7ff91f9e4010, len: 5 (0x5) align: 1] allocated at:main.zig:11:32: 0x11e4237 in main (main.zig) const bytes = try gpa.alloc(u8, 5); ^leaks: 1deinit writes a report for each leak and returns how many there were. Zig Memory Leaks shows how to read the report.
2. Run out on purpose
Section titled “2. Run out on purpose”Make a FixedBufferAllocator over an 8-byte buffer. In a loop, allocate 3 bytes at a time and print how many allocations worked before you got OutOfMemory.
Hint: while (true) { _ = a.alloc(u8, 3) catch break; count += 1; }.
Show solution
const std = @import("std");
pub fn main() void { var buffer: [8]u8 = undefined; var fba: std.heap.FixedBufferAllocator = .init(&buffer); const a = fba.allocator();
var count: u32 = 0; while (true) { _ = a.alloc(u8, 3) catch break; count += 1; } std.debug.print("{d} allocations fit\n", .{count});}Output:
2 allocations fitTwo allocations use 6 of the 8 bytes. A third needs 3 more, only 2 are left, so alloc fails and catch break leaves the loop.
init.gpais the default: a checkingSafeAllocatorindebugandsafebuilds, a fast allocator infastandsmall.- Allocators with state follow one shape:
var x = .init(...),x.allocator(),x.deinit(). page_allocatorgoes to the OS for every call. Use it mostly as a backing allocator.ArenaAllocatorfrees everything at once;FixedBufferAllocatoruses a buffer you own and fails when it’s full.BufferFirstAllocator(the oldStackFallbackAllocator) tries a buffer first, then falls back.DebugAllocatoris deprecated in 0.17. Libraries take an allocator instead of picking one.
Next up: Zig Arena Allocator, the allocator that frees everything at once, and init.arena.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Choosing an Allocator: the official flow chart.
- Zig 0.17.0 release notes: SafeAllocator Introduced: what the new checking allocator guarantees, and the
BufferFirstAllocatorrename right above it. - std.heap source (0.17.1): the list of allocators, each with a doc comment.
- Learning Zig: Heap Memory & Allocators: a community walk through the same choices, written for an older Zig.