man zig/allocators

Allocators in Zig: who owns the memory

lib / Zig 9 mindraft

checked against: Zig 0.17.1

Why does nearly every Zig function that can grow a container take an Allocator argument? What is that value, which one does main get when it asks for one, and does the choice change how fast a program runs?

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    var list: std.ArrayList(u64) = .empty;
    defer list.deinit(init.gpa);
    try list.append(init.gpa, 42);
}

This article reads the standard library at the 0.17.1 tag on Codeberg (the files there match the ones Homebrew installs byte for byte) and the release notes from 0.14.0 to 0.17.0. The experiments are small programs built with zig build-exe -O fast, or in debug mode where I say so, on an Apple M2 Pro running macOS. Every number comes from that source, those notes, or one of those programs.

The short version

An Allocator is a pointer to some state plus a pointer to a table of four functions. Nothing in the standard library allocates without being handed one, and the containers are moving toward taking it on every call instead of storing it. main can receive a general-purpose allocator and an arena in std.process.Init. Which general-purpose allocator that is depends on the build mode and on whether libc is linked; on macOS in -O fast it is malloc. For a program that allocates a few dozen times, the choice makes no measurable difference. For one that allocates a hundred thousand small objects, page_allocator is more than 200 times slower than malloc.

An Allocator is two pointers

std.mem.Allocator has two fields (mem/Allocator.zig L22-L23), ptr: *anyopaque and vtable: *const VTable, so it is 16 bytes on a 64-bit target, and it is passed by value. The VTable (L25-L87) has four entries:

alloc   give me len bytes with this alignment, or null
resize  grow or shrink in place; true or false
remap   grow or shrink, moving if needed; new pointer or null
free    give it back

Everything else, create, destroy, alloc(T, n), free, realloc, is a generic helper on top of those four. Allocators with no state of their own, such as page_allocator, set ptr to undefined, and the doc comment on ptr warns that comparing it “may result in illegal behavior.”

Because the interface is that small, wrapping one allocator in another takes a few lines. This one counts calls and forwards them:

const Counting = struct {
    child: std.mem.Allocator,
    allocs: usize = 0,

    fn allocator(self: *Counting) std.mem.Allocator {
        return .{ .ptr = self, .vtable = &.{
            .alloc = alloc, .resize = resize, .remap = remap, .free = free,
        } };
    }
    fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 {
        const self: *Counting = @ptrCast(@alignCast(ctx));
        self.allocs += 1;
        return self.child.rawAlloc(len, a, ra);
    }
    // resize, remap and free count and forward the same way
};

I used it on a program that reads 589 KB from stdin and counts 100,000 integers (43,282 distinct) in an AutoHashMapUnmanaged(u32, u32), then copies the pairs into an ArrayList:

$ zig build-exe -O fast count.zig && ./count < numbers.txt
input bytes=589095 read: allocs=1 resizes=0 remaps=1 frees=0
count: size=43282 capacity=65536 grows=14 allocs=14 frees=13 (since read)
pairs: allocs=1 resizes=0 remaps=17 capacity=50855
total: allocs=16 resizes=0 remaps=18 frees=13 bytes_requested=2063818 peak_live=1585783

Sixteen allocations for 100,000 inserts. The hash map allocates once per grow, and the list grows by remap. Keep that number in mind for the timings at the end.

Who holds the allocator

There used to be two of each container. A “managed” one had an Allocator field, and an “unmanaged” one that takes the allocator on every call that may allocate. 0.15.1 made std.ArrayList the unmanaged one and moved the old type to std.array_list.Managed, with the warning “these will both eventually be removed entirely.” Its notes give the reason. “Having an extra field is more complicated than not having an extra field, so not having it is the null hypothesis.” 0.16.0 removed the managed array hash maps and said “the variant without the allocator field is more versatile and the other one should be removed.” In 0.17.1 std.AutoHashMap, which stores its allocator, still exists next to std.AutoHashMapUnmanaged.

The difference in size is one Allocator, 16 bytes:

$ zig build-exe -O fast sizes.zig && ./sizes
AutoHashMap(u32, u32): 32 bytes, AutoHashMapUnmanaged(u32, u32): 16 bytes

The unmanaged style also means nothing checks at compile time that deinit gets the same allocator as append did. The ArrayList doc comment states the rule instead. “The same allocator must be used throughout its entire lifetime.”

What main gets

Since 0.16.0 main can take a std.process.Init (process.zig L31-L58), which the 0.16.0 release notes call “Juicy Main”. It carries gpa, “a default-selected general purpose allocator for temporary heap allocations”, and arena, “permanent storage for the entire process, cleaned automatically on exit.” start.zig builds both before calling main (L780-L835):

const use_safe_allocator = !is_wasm and switch (builtin.mode) {
    .debug, .safe => true,
    .fast, .small => !builtin.link_libc and builtin.single_threaded, // Also not ideal.
};
...
const gpa = if (use_safe_allocator)
    safe_allocator.allocator()
else if (builtin.link_libc)
    std.heap.c_allocator
else if (is_wasm)
    std.heap.wasm_allocator
else if (!builtin.single_threaded)
    std.heap.smp_allocator
else
    comptime unreachable;

The arena is an ArenaAllocator over page_allocator. On macOS libc is always linked, because std.Target.requiresLibC returns true for it (Target.zig L2304-L2318), so a -O fast build there gets c_allocator. I compared the vtable pointers to check:

$ zig build-exe -O fast gpa.zig && ./gpa
mode=fast link_libc=true single_threaded=false
smp=false c=true page=false
$ zig build-exe -O safe gpa.zig && ./gpa
mode=safe link_libc=true single_threaded=false
smp=false c=false page=false

On Linux without -lc, the same -O fast program would get smp_allocator, according to the same lines.

page_allocator: one mmap per call

PageAllocator.alloc (PageAllocator.zig L162-L167) calls map, which calls mmap (L133-L140) for whole pages, and free unmaps them. The M2’s pages are 16 KB, so a 1-byte allocation uses a full page:

page size 16384, @sizeOf(Allocator) 16
two 1-byte page_allocator allocations are 16384 bytes apart

It is meant as a backing allocator for others, and that is how start.zig uses it.

The arena

ArenaAllocator asks its child allocator for large nodes and hands out pieces of the current one by bumping an index. Its free (ArenaAllocator.zig L608-L630) only takes memory back when it is the most recent allocation; anything else is a no-op. deinit returns all nodes at once. A new node is sized from the previous node and the request, plus half again (L515-L517):

const min_size = @sizeOf(Node) + alignment.toByteUnits() + n;
const big_enough_size = prev_size + min_size + 16;
const size = mem.alignForward(usize, big_enough_size + big_enough_size / 2, 2);

0.16.0 rewrote it to be “Thread-Safe and Lock-Free”; the bump is an @atomicRmw on the node’s end index, and the release notes say a single thread sees “comparable performance to the previous one.”

The cost of an arena is memory that can’t be reused. A hash map that grows allocates a bigger table and frees the old one, and in an arena that free does nothing. Counting the same 100,000 integers into a map backed by an arena over the counting wrapper over page_allocator:

arena: page_allocator calls allocs=6 frees=0 resizes=10 remaps=0, arena capacity=2473808

The final table of 65,536 slots is about 590 KB. The arena held 2.47 MB, because the 13 earlier tables are still in it, along with the unused end of its last node. Six allocations and ten resize calls to page_allocator covered all of it.

SafeAllocator, new in 0.17

0.14.0 renamed GeneralPurposeAllocator to DebugAllocator. 0.17.0 deprecated that in turn (heap.zig L21-L24) for std.heap.SafeAllocator, “a thread-safe allocator” whose deinit “reports all leaks and frees all backing memory.” Its header comment (SafeAllocator.zig L1-L27) describes the design. Every allocation is followed by an AllocFooter with its metadata and stack trace, protected by a checksum. Over a backing allocator that doesn’t reuse memory it doesn’t reuse memory either, so most writes after a free fault. A debug build that forgets one free:

pub fn main(init: std.process.Init) !void {
    const list = try init.gpa.alloc(u32, 100);
    list[0] = 1; // never freed
}
$ zig build-exe leak.zig && ./leak; echo "exit $?"   # paths shortened
error(SafeAllocator): leaked [addr: 1025fe330, len: 400 (0x190) align: 4] allocated at:
.../leak.zig:4:36: 0x10249344f in main (leak)
    const list = try init.gpa.alloc(u32, 100);
                                   ^
.../lib/zig/std/start.zig:827:30: 0x1024939ab in callMain (leak)
    return wrapMain(root.main(.{
                             ^
???:?:?: 0x18d188d7b in start (/usr/lib/dyld)

exit 0

The exit status stays 0; start.zig says so in a comment, “Leaks do not affect return code” (L806). The same program built with -O fast prints nothing, because there init.gpa is malloc.

What each one costs

For many small objects the allocators differ a lot. This program builds a 100,000-node linked list of 16-byte nodes with create, then frees it from the oldest node on with destroy, timed in-process with std.Io.Timestamp:

$ zig build-exe -O fast alloc.zig && ./alloc
page_allocator     359532 us  (sum 4999950000)
c_allocator          1522 us  (sum 4999950000)
smp_allocator        1101 us  (sum 4999950000)
SafeAllocator        3609 us  (sum 4999950000)
ArenaAllocator       1215 us  (sum 4999950000)
arena still holds 1752840 bytes after every destroy
FixedBuffer           588 us  (sum 4999950000)

Three runs gave 354 to 371 ms for page_allocator, which calls mmap and munmap for every node and gives each 16-byte node its own 16 KB page. The others stayed within 10% of the numbers above across the three runs. SafeAllocator took about 2.4 times as long as malloc, for its footers and bookkeeping. FixedBufferAllocator, a bump pointer over a 4 MB buffer on the stack, was fastest. The arena still held 1.75 MB after the last destroy. An earlier version of the program that freed the newest node first printed the same number: queryCapacity counts the nodes the arena got from page_allocator, and those stay until deinit whatever is freed.

For the counting program from the start, the choice did not matter. I timed it as a whole process, input piped on stdin, startup included, taking the best of 11 runs, in two to six sessions per variant. With the map and list on init.gpa (malloc) it took 9.4 to 10.8 ms, on smp_allocator 9.4 to 10.7 ms, on init.arena 9.3 to 10.5 ms, and on page_allocator directly 9.2 to 10.4 ms. With sixteen allocations, there is nothing for an allocator to win.

Curious facts

  • The language reference’s “Choosing an Allocator” section at 0.17.1 still recommends std.heap.DebugAllocator in debug mode, which heap.zig at the same tag marks deprecated.
  • smp_allocator was introduced in 0.14.0 as “designed for ReleaseFast optimization mode, with multi-threading enabled,” and its release notes call it “about 200 lines of code and yet competitive with glibc performance.”
  • The Init doc comment calls init.arena “Threadsafe”. ArenaAllocator has been thread-safe since 0.16.0 made it lock-free.
  • 0.16.0 removed heap.ThreadSafeAllocator; the release notes call it “an anti-pattern.”
  • A leak found by SafeAllocator at exit is logged but leaves the exit status at 0.

History

  • 0.14.0 (2025-03-05): GeneralPurposeAllocator rewritten and renamed to DebugAllocator; SmpAllocator added; remap added to Allocator.VTable.
  • 0.15.1 (2025-08-19): std.ArrayList becomes the unmanaged list.
  • 0.16.0 (2026-04-13): main can take std.process.Init; all I/O takes an Io; ArenaAllocator becomes thread-safe and lock-free; ThreadSafeAllocator and the managed array hash maps are removed.
  • 0.17.0 (2026-10-01): SafeAllocator replaces DebugAllocator, which is deprecated.

Dates are from ziglang.org’s download index.

Sources

ls zig/