Skip to content

Allocators are passed in

30 September 2025 ยท Zig 0.15

Nothing in Zig allocates behind your back. A function that needs memory takes a std.mem.Allocator and says so in its signature, and the caller decides where the memory comes from: the heap, a fixed buffer, an arena freed all at once.

const std = @import("std");

test "a copy, and nothing leaked" {
    const allocator = std.testing.allocator;
    const copy = try allocator.dupe(u8, "hello");
    defer allocator.free(copy);
    copy[0] = 'j';
    try std.testing.expectEqualStrings("jello", copy);
}

std.testing.allocator fails the test if anything it handed out isn't freed, so the defer isn't optional. An arena turns many frees into one:

test "an arena frees everything at once" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const words = try a.alloc([]const u8, 3);
    for (words, 0..) |*w, i| w.* = try std.fmt.allocPrint(a, "word {d}", .{i});
    try std.testing.expectEqualStrings("word 2", words[2]);
}

0.15 changed std.ArrayList too: it no longer keeps its allocator, so every call that might allocate takes one, and .empty is a list with nothing in it yet.

test "a list that's handed its allocator" {
    const allocator = std.testing.allocator;
    var list: std.ArrayList(u32) = .empty;
    defer list.deinit(allocator);
    try list.append(allocator, 1);
    try list.appendSlice(allocator, &.{ 2, 3 });
    try std.testing.expectEqual(@as(usize, 3), list.items.len);
}