TExcelTAD
Home › Zig › Zig Allocators

Zig Allocators

So far all our data had a size known at compile time and lived on the stack. Real programs often need memory whose size is known only at runtime: a file's contents, a list of user input, a growing cache. That memory comes from the heap, and in Zig it always comes from an allocator that you pass in explicitly.

There is no global malloc. Any function that needs heap memory takes a std.mem.Allocator parameter, so you can see from its signature that it allocates — and you choose how.

The Allocator interface

Every allocator exposes the same std.mem.Allocator interface:

Method Purpose
alloc(T, n) allocate a slice of n items of type T
free(slice) release a slice from alloc
create(T) allocate a single T, returns *T
destroy(ptr) release a pointer from create
dupe(T, slice) allocate a copy of a slice
realloc(slice, n) resize, possibly moving the data

Allocation can fail, so these return error unions with error.OutOfMemory — hence the try.

page_allocator

std.heap.page_allocator asks the operating system for whole memory pages. It is simple and always available, but every allocation costs at least one page (usually 4 KiB), so it is wasteful for many small allocations.

zig · try it yourself
const std = @import("std");

pub fn main() !void {
    const allocator = std.heap.page_allocator;

    const count: usize = 5; // imagine this came from user input
    const squares = try allocator.alloc(u64, count);
    defer allocator.free(squares);

    for (squares, 0..) |*s, i| s.* = i * i;
    std.debug.print("{any}\n", .{squares});

    const copy = try allocator.dupe(u8, "heap text");
    defer allocator.free(copy);
    copy[0] = 'H';
    std.debug.print("{s}\n", .{copy});
}
{ 0, 1, 4, 9, 16 }
Heap text

DebugAllocator: find leaks and bugs

std.heap.DebugAllocator (called GeneralPurposeAllocator in older versions — the old name still works in 0.15) is the allocator to use while developing. It detects memory leaks, double frees and use-after-free. Its deinit reports whether anything leaked:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    var debug_alloc: std.heap.DebugAllocator(.{}) = .init;
    const allocator = debug_alloc.allocator();

    const numbers = allocator.alloc(i32, 3) catch return;
    numbers[0] = 1;
    numbers[1] = 2;
    numbers[2] = 3;
    std.debug.print("numbers: {any}\n", .{numbers});
    allocator.free(numbers);

    const status = debug_alloc.deinit();
    std.debug.print("leak check: {t}\n", .{status});
}
numbers: { 1, 2, 3 }
leak check: ok

If you remove the free line, deinit returns .leak and prints the stack trace of the leaked allocation. The usual setup is defer _ = debug_alloc.deinit(); at the top of main.

FixedBufferAllocator: no heap at all

std.heap.FixedBufferAllocator hands out memory from a buffer you provide — often a stack array. It is extremely fast, never calls the OS, and fails with OutOfMemory when the buffer is full. Ideal for embedded systems and predictable memory use:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    var buffer: [64]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&buffer);
    const allocator = fba.allocator();

    const a = allocator.alloc(u8, 40) catch unreachable;
    @memset(a, 'x');
    std.debug.print("got {d} bytes\n", .{a.len});

    if (allocator.alloc(u8, 40)) |b| {
        std.debug.print("got another {d} bytes\n", .{b.len});
    } else |err| {
        std.debug.print("second allocation failed: {t}\n", .{err});
    }
    std.debug.print("used {d} of {d} bytes\n", .{ fba.end_index, buffer.len });
}
got 40 bytes
second allocation failed: OutOfMemory
used 40 of 64 bytes

ArenaAllocator: free everything at once

An arena wraps another allocator. You allocate as much as you like and never free individual items; arena.deinit() releases everything in one go. Perfect for work with a clear lifetime: one request, one frame of a game, one command-line run.

zig · try it yourself
const std = @import("std");

pub fn main() !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit(); // frees all three strings below

    const allocator = arena.allocator();
    const names = [_][]const u8{ "ana", "bao", "cyrus" };
    for (names, 1..) |name, i| {
        const line = try std.fmt.allocPrint(allocator, "#{d}: {s} ({d} letters)", .{ i, name, name.len });
        std.debug.print("{s}\n", .{line});
    }
}
#1: ana (3 letters)
#2: bao (3 letters)
#3: cyrus (5 letters)

Single items: create and destroy

zig
const node = try allocator.create(Node);
defer allocator.destroy(node);
node.* = .{ .value = 42, .next = null };

Choosing an allocator

Allocator Best for
DebugAllocator(.{}) development and tests (leak detection)
std.heap.smp_allocator fast general-purpose allocator for release builds
std.heap.c_allocator when linking libc anyway (uses malloc)
ArenaAllocator many allocations sharing one lifetime
FixedBufferAllocator bounded memory, no OS calls
std.testing.allocator inside tests (fails the test on leaks)
page_allocator large, long-lived blocks; backing an arena

Tip: Write library functions to take allocator: std.mem.Allocator and let the caller decide. The same code then works with an arena in a web server, a fixed buffer on a microcontroller and the testing allocator in unit tests.

Test yourself

How does a Zig function signal that it may allocate heap memory?

  1. It is marked alloc
  2. It takes an std.mem.Allocator parameter
  3. It returns a pointer
  4. It can't be known

What is the main advantage of an ArenaAllocator?

  1. It detects leaks
  2. Everything is freed with a single deinit
  3. It uses no memory
  4. It is thread-local

What does FixedBufferAllocator return when its buffer is full?

  1. null
  2. A larger buffer from the OS
  3. error.OutOfMemory
  4. It panics always