Skip to content

Zig Testing Allocator

In Zig you free memory yourself, so sooner or later you’ll forget to. The good news: you don’t have to find those mistakes by staring at code. Every test can use std.testing.allocator, an allocator that keeps track of everything you allocate and fails the test if anything is left over at the end. Add FailingAllocator and you can also test the paths most programs never test: what happens when memory runs out halfway through. This page shows both, with the real output you’ll get when they catch something.

Any function that needs memory takes an allocator (that’s the rule from Zig Allocators). In a test, you hand it std.testing.allocator:

const std = @import("std");
fn words(gpa: std.mem.Allocator, text: []const u8) ![][]const u8 {
var list: std.ArrayList([]const u8) = .empty;
errdefer list.deinit(gpa);
var it = std.mem.tokenizeScalar(u8, text, ' ');
while (it.next()) |word| try list.append(gpa, word);
return list.toOwnedSlice(gpa);
}
test "words splits on spaces" {
const gpa = std.testing.allocator;
const result = try words(gpa, "the quick fox");
defer gpa.free(result);
try std.testing.expectEqual(3, result.len);
try std.testing.expectEqualStrings("quick", result[1]);
}

Output:

1/1 main.test.words splits on spaces...OK
All 1 tests passed.

words builds a list of the words (tokenizeScalar skips the double space), then hands the memory to the caller with toOwnedSlice. The caller owns it now, so the test frees it with defer gpa.free(result). Nothing leaks, so the test passes quietly.

std.testing.allocator is a SafeAllocator, the same checking allocator you get from init.gpa in debug builds. The test runner gives every test a fresh one and checks it when the test ends. The language reference shows the same check in its Report Memory Leaks example.

Now delete the defer gpa.free(result); line and run zig test main.zig again. You’ll see something like this (paths shortened, addresses change every run):

1/1 main.test.words splits on spaces...OK
[SafeAllocator] (err): leaked [addr: 7f53d9756070, len: 48 (0x30) align: 8] allocated at:
.../lib/std/array_list.zig:751:26: 0x125469e in toOwnedSlice (std.zig)
if (gpa.remap(old_memory, self.items.len)) |new_items| {
^
main.zig:8:29: 0x124efe0 in words (main.zig)
return list.toOwnedSlice(gpa);
^
main.zig:13:29: 0x124f4e3 in test.words splits on spaces (main.zig)
const result = try words(gpa, "the quick fox");
^
(more lines from the test runner)
All 1 tests passed.
1 errors were logged.
1 tests leaked memory.
error: the following test command failed with exit code 1:

Read it from the top:

  • OK, then All 1 tests passed. The checks inside the test all passed. Don’t stop reading there.
  • leaked [... len: 48 ...]: 48 bytes were never freed. That’s three slices of 16 bytes each (a pointer and a length), the three words.
  • The trace shows where the memory was allocated: in toOwnedSlice, called from words on line 8, called from the test on line 13. It can’t show where you should have freed it; that part is up to you.
  • 1 tests leaked memory. and exit code 1: the run as a whole fails. In CI, a leak breaks the build just like a wrong answer.

The leak report comes after the test’s own line because the check happens when the test is finished and its allocator is torn down.

The testing allocator catches more than leaks. Freeing the same memory twice is a bug that can corrupt memory in a release build. Here it stops the test on the spot:

const std = @import("std");
test "double free" {
const gpa = std.testing.allocator;
const buf = try gpa.alloc(u8, 4);
gpa.free(buf);
gpa.free(buf);
}

You’ll see something like:

1/1 main.test.double free...thread 30679 panic: double free of [addr: 7f60bdb4e010, len: 4 (0x4) align: 1]
alloc:
main.zig:5:30: 0x124ee67 in test.double free (main.zig)
const buf = try gpa.alloc(u8, 4);
^
(more lines)
first free:
main.zig:6:13: 0x124eed2 in test.double free (main.zig)
gpa.free(buf);
^

It’s a panic, not a test failure, so the whole test run stops here. You get three traces: where the memory was allocated, where it was freed the first time (first free:), and the second free that crashed.

Writing into memory after freeing it is caught too, when the test ends and the allocator checks its freed memory:

const std = @import("std");
test "use after free" {
const gpa = std.testing.allocator;
const buf = try gpa.alloc(u8, 4);
gpa.free(buf);
buf[0] = 'x';
}

You’ll see the test print OK, then panic: write after free at *7fbed72b2010, followed by traces for the original allocation and the free. Reading freed memory isn’t caught this way, only writing, so don’t take a quiet run as proof that a slice is still valid.

Every try gpa.alloc(...) can fail with error.OutOfMemory, and your code has an answer for that case whether you thought about it or not. On a laptop with gigabytes free, that answer never runs, so it’s never tested. std.testing.FailingAllocator fixes that. It wraps another allocator and makes one chosen allocation fail.

Here’s a Badge that needs two allocations. There’s a bug in it, so read create carefully:

const std = @import("std");
const Badge = struct {
name: []u8,
title: []u8,
fn create(gpa: std.mem.Allocator, name: []const u8) !Badge {
const name_copy = try gpa.dupe(u8, name);
const title = try gpa.print("Hello, I'm {s}!", .{name});
return .{ .name = name_copy, .title = title };
}
fn destroy(self: Badge, gpa: std.mem.Allocator) void {
gpa.free(self.title);
gpa.free(self.name);
}
};
test "create fails cleanly when the second allocation fails" {
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 });
const result = Badge.create(failing.allocator(), "Ada");
try std.testing.expectError(error.OutOfMemory, result);
}

.fail_index = 1 means “let allocation 0 work, fail allocation 1”. So dupe works and print fails. The test expects error.OutOfMemory, and it gets it. But you’ll see:

1/1 main.test.create fails cleanly when the second allocation fails...OK
[SafeAllocator] (err): leaked [addr: 7ff7919ea010, len: 3 (0x3) align: 1] allocated at:
.../lib/std/mem/Allocator.zig:481:40: 0x106f5ce in dupe__func_109 (std.zig)
main.zig:8:39: 0x124ee94 in create (main.zig)
(more lines)
All 1 tests passed.
1 errors were logged.
1 tests leaked memory.

There’s the bug: when print fails, the copy of "Ada" (3 bytes) is never freed. Notice the team-up here: FailingAllocator forces the rare path to run, and the testing allocator underneath it notices the leak. The fix is one line, an errdefer right after the first allocation:

const std = @import("std");
const Badge = struct {
name: []u8,
title: []u8,
fn create(gpa: std.mem.Allocator, name: []const u8) !Badge {
const name_copy = try gpa.dupe(u8, name);
errdefer gpa.free(name_copy);
const title = try gpa.print("Hello, I'm {s}!", .{name});
return .{ .name = name_copy, .title = title };
}
fn destroy(self: Badge, gpa: std.mem.Allocator) void {
gpa.free(self.title);
gpa.free(self.name);
}
};
test "create works" {
const gpa = std.testing.allocator;
const badge = try Badge.create(gpa, "Ada");
defer badge.destroy(gpa);
try std.testing.expectEqualStrings("Hello, I'm Ada!", badge.title);
}
test "create fails cleanly when the second allocation fails" {
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 });
const result = Badge.create(failing.allocator(), "Ada");
try std.testing.expectError(error.OutOfMemory, result);
}

Output:

1/2 main.test.create works...OK
2/2 main.test.create fails cleanly when the second allocation fails...OK
All 2 tests passed.

The FailingAllocator source is short if you want to see how it counts. Two things to get right with it:

  • It must be a var, and you pass failing.allocator(), because the wrapper counts allocations inside itself.
  • Wrap std.testing.allocator, not some other allocator, so leaks on the failure path are still caught.

Try every failure at once: checkAllAllocationFailures

Section titled “Try every failure at once: checkAllAllocationFailures”

Picking fail_index by hand gets tedious: a function with five allocations needs five tests, and you have to count them right. std.testing.checkAllAllocationFailures does it for you. It runs your function once to count its allocations, then runs it again with allocation 0 failing, then allocation 1, and so on, checking for leaks every time.

Your function has to take the allocator as its first parameter and return !void, so write a small helper that does the work and cleans up:

const std = @import("std");
const Badge = struct {
name: []u8,
title: []u8,
fn create(gpa: std.mem.Allocator, name: []const u8) !Badge {
const name_copy = try gpa.dupe(u8, name);
errdefer gpa.free(name_copy);
const title = try gpa.print("Hello, I'm {s}!", .{name});
return .{ .name = name_copy, .title = title };
}
fn destroy(self: Badge, gpa: std.mem.Allocator) void {
gpa.free(self.title);
gpa.free(self.name);
}
};
fn createAndDestroy(gpa: std.mem.Allocator) !void {
const badge = try Badge.create(gpa, "Ada");
badge.destroy(gpa);
}
test "Badge.create survives every allocation failure" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, createAndDestroy, .{});
}

Output:

1/1 main.test.Badge.create survives every allocation failure...OK
All 1 tests passed.

The last argument, .{}, holds any extra arguments for your helper after the allocator (none here). Take the errdefer out again and the same test catches the leak and tells you which allocation it made fail:

1/1 main.test.Badge.create survives every allocation failure...
fail_index: 1/3
allocated bytes: 3
freed bytes: 0
allocations: 1
deallocations: 0
allocation that was made to fail:
.../lib/std/mem/Allocator.zig:507:55: 0x1250f81 in print__func_963 (std.zig)
main.zig:9:36: 0x124ef4b in create (main.zig)
const title = try gpa.print("Hello, I'm {s}!", .{name});
^
(more lines)
FAIL (MemoryLeakDetected)

fail_index: 1/3 says the function makes 3 allocations in a normal run (print makes two of them on its own) and failing number 1 is the one that leaked. “allocated bytes: 3, freed bytes: 0” is the "Ada" copy again.

std.testing.allocator only exists in test builds. Use it in a normal program and you get a compile error that’s short and to the point:

const std = @import("std");
pub fn main() !void {
const gpa = std.testing.allocator;
const buf = try gpa.alloc(u8, 4);
defer gpa.free(buf);
}
.../lib/std/testing.zig:21:80: error: not testing
pub const allocator = if (builtin.is_test) allocator_instance.allocator() else @compileError("not testing");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~

In a real program, use init.gpa (see Zig Choosing an Allocator). It runs the same leak checks in debug builds and prints a similar report when the program ends. This is one more reason to write functions that take an allocator: the program passes init.gpa, the tests pass std.testing.allocator or a FailingAllocator, and the function doesn’t care.

This test leaks. Find it with zig test and fix it without changing repeat.

fn repeat(gpa: std.mem.Allocator, text: []const u8, times: usize) ![]u8 {
const out = try gpa.alloc(u8, text.len * times);
for (0..times) |i| @memcpy(out[i * text.len ..][0..text.len], text);
return out;
}
test "repeat" {
const result = try repeat(std.testing.allocator, "ab", 3);
try std.testing.expectEqualStrings("ababab", result);
}

Hint: the leak report points at the alloc inside repeat. Who owns out once repeat returns?

Show solution
const std = @import("std");
fn repeat(gpa: std.mem.Allocator, text: []const u8, times: usize) ![]u8 {
const out = try gpa.alloc(u8, text.len * times);
for (0..times) |i| @memcpy(out[i * text.len ..][0..text.len], text);
return out;
}
test "repeat" {
const gpa = std.testing.allocator;
const result = try repeat(gpa, "ab", 3);
defer gpa.free(result);
try std.testing.expectEqualStrings("ababab", result);
}

Output:

1/1 main.test.repeat...OK
All 1 tests passed.

repeat hands its memory to the caller, so the caller (the test) frees it. Keeping the allocator in a gpa constant makes sure you free with the same allocator you allocated with.

Write fn fullName(gpa: std.mem.Allocator, first: []const u8, last: []const u8) ![2][]u8 that returns upper-case copies of both names (use std.ascii.allocUpperString(gpa, text)). Check it with checkAllAllocationFailures.

Hint: the helper for checkAllAllocationFailures can take extra arguments: fn helper(gpa: std.mem.Allocator, first: []const u8, last: []const u8) !void, called with .{ "ada", "lovelace" }.

Show solution
const std = @import("std");
fn fullName(gpa: std.mem.Allocator, first: []const u8, last: []const u8) ![2][]u8 {
const a = try std.ascii.allocUpperString(gpa, first);
errdefer gpa.free(a);
const b = try std.ascii.allocUpperString(gpa, last);
return .{ a, b };
}
fn useFullName(gpa: std.mem.Allocator, first: []const u8, last: []const u8) !void {
const names = try fullName(gpa, first, last);
defer for (names) |name| gpa.free(name);
try std.testing.expectEqualStrings("LOVELACE", names[1]);
}
test "fullName with every allocation failing" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, useFullName, .{ "ada", "lovelace" });
}

Output:

1/1 main.test.fullName with every allocation failing...OK
All 1 tests passed.

Without the errdefer, the run where the second allocation fails would leak "ADA" and the test would fail with MemoryLeakDetected. The checks inside the helper run too, on the one run where nothing fails.

  • std.testing.allocator is a checking allocator, fresh for every test. Use it in every test that allocates.
  • A leak shows leaked [...] with the size and where it was allocated, plus 1 tests leaked memory., and the run fails even though the test printed OK.
  • Double frees and writes after free make the test panic with traces of the allocation and the free.
  • FailingAllocator makes allocation number fail_index fail, so you can test the out-of-memory path. Wrap std.testing.allocator so leaks there are caught too.
  • checkAllAllocationFailures fails each allocation in turn and checks for leaks every time.
  • The testing allocator only exists in tests; programs use init.gpa.

Next up: Zig Testing Extras, for skipping tests, filtering, testing code that does I/O, and fuzzing.

Quick check

1. A test prints OK but then 1 tests leaked memory. Did the test run succeed?
2. What does FailingAllocator.init(std.testing.allocator, .{ .fail_index = 2 }) do?
3. Why wrap std.testing.allocator inside the FailingAllocator?
4. What happens if you use std.testing.allocator inside main?