Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Allocators and Error Handling

Allocators in Zig

Learn why Zig passes allocators explicitly, and how the page, arena, fixed-buffer and debug allocators differ, with diagrams, examples and a runnable arena stand-in.

In many languages, memory just appears: you write new or build a list, and a hidden global allocator finds the bytes. Zig takes a different road. There is no hidden allocator. Any function that needs heap memory takes an std.mem.Allocator parameter, and you decide which kind of allocator to hand it. The language itself never allocates behind your back.

This rule has big payoffs. You can see from a function signature whether it may allocate. You can test code with an allocator that detects leaks. You can switch a program from "malloc for everything" to "one arena that is freed at the end" by changing a single line. And the same library code runs on a microcontroller with a fixed 4 KB buffer.

The Zig examples in this chapter target Zig 0.15. The standard library still moves between releases, so if a function name does not compile, check the release notes of your version. Zig cannot run on this site, so the Zig blocks are read-only; runnable stand-ins are written in Go and say so.

The Allocator interface

std.mem.Allocator is a small struct holding a pointer and a table of functions (alloc, resize, remap, free). It works like an interface in other languages. Every allocator implementation in the standard library gives you one through a method called .allocator() (or a plain field for some).

ZIG
const std = @import("std");

fn makeGreeting(gpa: std.mem.Allocator, name: []const u8) ![]u8 {
    return std.fmt.allocPrint(gpa, "Hello, {s}!", .{name});
}

The function does not know or care which allocator it received. By convention the parameter is named gpa or allocator, and it is the first parameter (after self in methods). The ! in the return type means "may fail": allocation can run out of memory, and Zig makes that visible (see Error unions and try).

The standard allocators

Allocator Gets memory from Frees Best for
std.heap.page_allocator the OS, whole pages each block simple tools, backing other allocators
std.heap.c_allocator C malloc/free (needs -lc) each block speed, interop with C
std.heap.DebugAllocator a backing allocator each block, checks leaks development and tests
std.heap.ArenaAllocator a backing allocator everything at once per-request or per-parse work
std.heap.FixedBufferAllocator a slice you provide reset only no-heap code, embedded
std.testing.allocator like DebugAllocator each block, fails tests on leaks unit tests
flowchart TD
  A["your function<br/>(takes std.mem.Allocator)"] --> B{"which one was passed?"}
  B --> C["DebugAllocator<br/>tracks leaks"]
  B --> D["ArenaAllocator<br/>free all at once"]
  B --> E["FixedBufferAllocator<br/>stack buffer"]
  C --> F["page_allocator / OS"]
  D --> F
  E --> G["no OS calls"]

Caption: the same function can sit on top of very different memory strategies.

The debug allocator

During development, create a DebugAllocator in main, and check at exit that nothing leaked:

ZIG
pub fn main() !void {
    var debug_allocator: std.heap.DebugAllocator(.{}) = .init;
    defer {
        const status = debug_allocator.deinit();
        if (status == .leak) std.debug.print("memory leaked!\n", .{});
    }
    const gpa = debug_allocator.allocator();

    const msg = try makeGreeting(gpa, "Zig");
    defer gpa.free(msg);
    std.debug.print("{s}\n", .{msg});
}

Forget the defer gpa.free(msg) line and the program reports the leak with a stack trace pointing at the allocation. In release builds many people switch to std.heap.smp_allocator or c_allocator for speed; a common pattern chooses by build mode.

The arena allocator

An arena hands out memory by bumping a pointer, and frees everything in one deinit. Individual free calls are no-ops. That makes it ideal for short tasks with many small allocations: parsing a file, handling a request, running one frame of a game.

ZIG
pub fn main() !void {
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena.deinit(); // frees every allocation below
    const a = arena.allocator();

    const one = try a.dupe(u8, "alpha");
    const two = try a.dupe(u8, "beta");
    std.debug.print("{s} {s}\n", .{ one, two });
    // no frees needed
}

The trade-off: memory is held until the arena dies, so do not use one for a long-running loop that allocates and discards.

The fixed buffer allocator

FixedBufferAllocator carves memory out of an array you supply. When the buffer is full, allocation returns error.OutOfMemory. Nothing touches the OS, so it is perfect for embedded code and predictable latency.

ZIG
var buffer: [1024]u8 = undefined;
var fba: std.heap.FixedBufferAllocator = .init(&buffer);
const gpa = fba.allocator();

const numbers = try gpa.alloc(u32, 10); // 40 bytes from the buffer
_ = numbers;

A runnable stand-in

Go has a garbage collector, so it does not need allocators, but we can model the idea of a bump arena to feel how it works. This is a Go stand-in, not Zig: a buffer slice, an offset, and a reset.

Go Stand-in: a bump (arena) allocator in Go

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The third allocation in each round fails: that is exactly what FixedBufferAllocator does with error.OutOfMemory. And Reset is the whole idea behind ArenaAllocator.deinit and FixedBufferAllocator.reset.

Choosing an allocator

  • Library code: never pick for the caller. Accept std.mem.Allocator.
  • main of an application: create one allocator at the top and pass it down. Use DebugAllocator while developing.
  • Short, bulk work: wrap the parent allocator in an arena.
  • Tests: use std.testing.allocator, which fails the test on any leak (see Testing in Zig).
  • Strictly bounded memory: use a fixed buffer.

Common mistakes

  • Creating an allocator inside a library function and returning memory from it. The caller then cannot free the memory properly.
  • Freeing memory with a different allocator than the one that allocated it. This is undefined behavior.
  • Using the arena's free and expecting memory back; it only comes back on deinit or reset.
  • Copying an allocator-owning struct (DebugAllocator, ArenaAllocator) after calling .allocator(): the interface holds a pointer to the original, so keep it in one place.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do Zig functions that allocate take an allocator parameter?

    Zig has no hidden global allocator. The parameter makes allocation visible and lets callers pick arenas, fixed buffers or debug allocators.
  2. 2. When is memory of an ArenaAllocator released?

    An arena ignores individual frees and releases everything on deinit (or reset), which makes bulk cleanup cheap.
  3. 3. What does a FixedBufferAllocator return when its buffer is full?

    It cannot grow, so allocation fails with error.OutOfMemory, which you handle like any other error.
  4. 4. Which allocator is best for catching leaks while developing?

    DebugAllocator tracks every allocation and reports leaks (with stack traces) when you call deinit.

Summary

  • Zig has no hidden allocator; functions that allocate take a std.mem.Allocator.
  • page_allocator and c_allocator talk to the OS or libc; DebugAllocator finds leaks; ArenaAllocator frees everything at once; FixedBufferAllocator uses a buffer you provide.
  • Libraries accept an allocator, applications choose one in main.
  • Always free with the allocator that allocated.

Next: Allocating and freeing memory