Skip to content

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.

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 Ana

What’s behind init.gpa depends on the build mode. We checked this in the 0.17.1 source (lib/std/start.zig):

  • In debug and safe builds, it’s a std.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 fast and small builds, it’s a faster allocator with no checks: std.heap.smp_allocator normally, or C’s malloc (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: 0

Three steps, and you’ll see this shape with every allocator that has its own state:

  1. Make the allocator’s state as a var (here safe), with .init(...). SafeAllocator takes a backing allocator, the place it gets its big chunks of memory from, and options (.{} means the defaults).
  2. Get the std.mem.Allocator interface from it with .allocator(), and pass that around.
  3. Clean up the state with deinit() at the end. For SafeAllocator, deinit reports 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 4096

You 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.

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 16
second: OutOfMemory
after reset: used 0

buffer 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: true
big came from the buffer: false

The 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.

  • std.heap.smp_allocator: a fast general-purpose allocator for fast builds with several threads. It’s what init.gpa becomes in a fast build without libc.
  • std.heap.c_allocator: C’s malloc and free. Use it when you link libc anyway (zig run -lc main.zig); without -lc it’s a compile error.
  • std.testing.allocator: only inside test blocks. 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.

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:

  1. Writing a library? Don’t pick. Take a std.mem.Allocator parameter and let the user decide.
  2. Writing a test? std.testing.allocator.
  3. Know the most memory you’ll need? FixedBufferAllocator (or BufferFirstAllocator if you’re only usually under it).
  4. Everything can be freed at the same moment (end of the program, end of a request)? ArenaAllocator.
  5. Anything else? init.gpa. It checks your work in debug and goes fast in fast.

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: 1

deinit writes a report for each leak and returns how many there were. Zig Memory Leaks shows how to read the report.

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 fit

Two 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.gpa is the default: a checking SafeAllocator in debug and safe builds, a fast allocator in fast and small.
  • Allocators with state follow one shape: var x = .init(...), x.allocator(), x.deinit().
  • page_allocator goes to the OS for every call. Use it mostly as a backing allocator.
  • ArenaAllocator frees everything at once; FixedBufferAllocator uses a buffer you own and fails when it’s full.
  • BufferFirstAllocator (the old StackFallbackAllocator) tries a buffer first, then falls back.
  • DebugAllocator is 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

1. What is init.gpa in a debug build with Zig 0.17.1?
2. You are writing a library function that needs memory. Which allocator should it use?
3. A FixedBufferAllocator over a 16-byte buffer has 10 bytes used. What happens when you ask for 10 more?
4. Why is page_allocator a poor choice for many small allocations?