Skip to content

Zig Memory Leaks

A memory leak is memory you allocated and never gave back. In a garbage-collected language, the runtime finds it for you. In Zig, nobody frees it, so it stays taken until the program exits. The good news: you don’t have to hunt for leaks by hand. In debug builds, init.gpa keeps a record of every allocation and, when the program ends, tells you exactly which ones you forgot and the line that made them. This lesson shows you how to read that report and how to fix the leaks it finds.

Let’s be honest first. When a program exits, the operating system takes back all its memory, leaks included. So a small tool that runs for a second and leaks a few bytes doesn’t hurt anyone.

Leaks matter when memory keeps piling up:

  • Long-running programs like servers, games and editors. A leak of a few bytes per request becomes gigabytes after a week.
  • Loops. A leak inside a loop that runs a million times is a million leaks.
  • Libraries. You don’t know how other people will call your code, so it must clean up after itself.

So treat every leak report as a bug, even in small programs. It’s much easier to keep a program leak-free from the start than to find leaks later.

Here’s a program that forgets two frees:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const name = try gpa.dupe(u8, "Ziggy");
std.debug.print("name: {s}\n", .{name});
const nums = try gpa.alloc(u32, 3);
_ = nums;
}

You’ll see something like:

name: Ziggy
error(SafeAllocator): leaked [addr: 7f89ac3c59f8, len: 12 (0xc) align: 4] allocated at:
main.zig:9:31: 0x11e42ae in main (main.zig)
const nums = try gpa.alloc(u32, 3);
^
error(SafeAllocator): leaked [addr: 7f89ac3c5968, len: 5 (0x5) align: 1] allocated at:
lib/std/mem/Allocator.zig:481:40: 0x10545ce in dupe__func_109 (std.zig)
const new_buf = try allocator.alloc(T, m.len);
^
main.zig:6:30: 0x11e41f3 in main (main.zig)
const name = try gpa.dupe(u8, "Ziggy");
^

We trimmed a few lines from the end of each report that point inside Zig’s own start-up code. Your addresses and paths will differ. Here’s how to read one report:

  • error(SafeAllocator): leaked: the allocator in init.gpa (a SafeAllocator in debug builds) found memory that was never freed.
  • len: 12 (0xc): how many bytes leaked. 3 u32s are 12 bytes. The second report’s len: 5 is the 5 letters of "Ziggy".
  • align: 4: the alignment of the memory. You can usually ignore it.
  • allocated at: and a stack trace: the chain of calls that made the allocation, innermost first.

The trace is the useful part. Read down until you reach your own file. In the second report, the first line is inside the standard library (dupe calls alloc), and the next one, main.zig:6:30, is the line you wrote. That’s where the missing free belongs.

The fix for most leaks is the pattern from Zig Defer: free right after you allocate.

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const name = try gpa.dupe(u8, "Ziggy");
defer gpa.free(name);
std.debug.print("name: {s}\n", .{name});
const nums = try gpa.alloc(u32, 3);
defer gpa.free(nums);
@memset(nums, 0);
}

Output:

name: Ziggy

No report means no leaks. That silence is what you’re aiming for.

Leaks in loops are the ones that hurt, because each round adds one more:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
for (0..3) |i| {
const line = try gpa.print("line {d}", .{i});
std.debug.print("{s}\n", .{line});
}
}

You’ll see three reports, one per round, all pointing at the same line:

line 0
line 1
line 2
error(SafeAllocator): leaked [addr: 7f206e903ab8, len: 6 (0x6) align: 1] allocated at:
...
main.zig:6:35: 0x11e4226 in main (main.zig)
const line = try gpa.print("line {d}", .{i});
^

The same line appearing again and again in the report is the sign of a leak in a loop. The fix is a defer inside the loop body, which runs at the end of every round:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
for (0..3) |i| {
const line = try gpa.print("line {d}", .{i});
defer gpa.free(line);
std.debug.print("{s}\n", .{line});
}
}

Output:

line 0
line 1
line 2

This one is sneaky. The function below copies some text, checks that it’s all digits, and returns the copy. It works for good input. But when the check fails, it returns an error, and the copy is never freed:

const std = @import("std");
fn parseAge(gpa: std.mem.Allocator, text: []const u8) ![]u8 {
const copy = try gpa.dupe(u8, text);
for (copy) |c| {
if (!std.ascii.isDigit(c)) return error.NotANumber;
}
return copy;
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const inputs = [_][]const u8{ "42", "forty", "7" };
for (inputs) |text| {
const age = parseAge(gpa, text) catch |err| {
std.debug.print("{s}: {s}\n", .{ text, @errorName(err) });
continue;
};
defer gpa.free(age);
std.debug.print("{s}: ok\n", .{age});
}
}

You’ll see something like:

42: ok
forty: NotANumber
7: ok
error(SafeAllocator): leaked [addr: 7f2beadb19f8, len: 5 (0x5) align: 1] allocated at:
...
main.zig:4:30: 0x11e4194 in parseAge (main.zig)
const copy = try gpa.dupe(u8, text);
^
main.zig:15:29: 0x11e450a in main (main.zig)
const age = parseAge(gpa, text) catch |err| {
^

len: 5 is "forty", the one input that failed. main can’t free it, because it never got the slice: it got an error instead. And parseAge can’t use a plain defer gpa.free(copy), because on success the caller needs the copy.

The answer is errdefer: cleanup that runs only when the function returns an error:

const std = @import("std");
fn parseAge(gpa: std.mem.Allocator, text: []const u8) ![]u8 {
const copy = try gpa.dupe(u8, text);
errdefer gpa.free(copy);
for (copy) |c| {
if (!std.ascii.isDigit(c)) return error.NotANumber;
}
return copy;
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const inputs = [_][]const u8{ "42", "forty", "7" };
for (inputs) |text| {
const age = parseAge(gpa, text) catch |err| {
std.debug.print("{s}: {s}\n", .{ text, @errorName(err) });
continue;
};
defer gpa.free(age);
std.debug.print("{s}: ok\n", .{age});
}
}

Output:

42: ok
forty: NotANumber
7: ok

One added line. On success, errdefer is skipped and the caller gets the copy; on error, the copy is freed before the error goes up. Whenever a function allocates something it will return, put an errdefer right after it. Zig Errdefer covers it in full.

A few more patterns that show up in leak reports:

  • Losing the only pointer. buf = try gpa.alloc(u8, 100); and later buf = try gpa.alloc(u8, 200); leaks the first 100 bytes: nothing points at them any more, so nothing can free them. Free the old one first, or use realloc.
  • Freeing the outside but not the inside. If a struct holds a slice you allocated, destroying the struct doesn’t free the slice. Give the struct a deinit that frees what it owns. Zig Lifetimes & Ownership shows this pattern.
  • Forgetting deinit on a collection. An ArrayList or HashMap allocates as it grows. Write defer list.deinit(gpa); right after you create it.

The same checking allocator catches two other bugs, too: freeing memory twice and writing to memory after freeing it. Both stop the program with a panic and a stack trace. You’ll see them in Zig Lifetimes & Ownership.

Tests are where leak checking really pays off, because a test fails when it leaks. Inside a test block, use std.testing.allocator:

const std = @import("std");
fn shout(allocator: std.mem.Allocator, text: []const u8) ![]u8 {
const out = try allocator.alloc(u8, text.len);
for (text, out) |c, *o| o.* = std.ascii.toUpper(c);
return out;
}
test "shout makes text upper case" {
const loud = try shout(std.testing.allocator, "hi");
try std.testing.expectEqualStrings("HI", loud);
}

Run it with zig test main.zig. You’ll see something like:

1/1 main.test.shout makes text upper case...OK
[SafeAllocator] (err): leaked [addr: 7fa8ff8b6010, len: 2 (0x2) align: 1] allocated at:
main.zig:4:36: 0x124eeac in shout (main.zig)
const out = try allocator.alloc(u8, text.len);
^
...
All 1 tests passed.
1 errors were logged.
1 tests leaked memory.
error: the following test command failed with exit code 1:

The check passed (OK), but the test run still fails, with 1 tests leaked memory. and exit code 1. That’s exactly what you want in a test suite. Adding defer std.testing.allocator.free(loud); after the call fixes it. Zig Testing Allocator has more on this, including how to test what happens when memory runs out.

In fast and small builds, init.gpa is a fast allocator with no bookkeeping, so it never reports leaks. That’s by design: checks cost time and memory. So do your leak hunting in a debug build (the default for zig run and zig test), and make sure your tests run in one. The language reference on optimization modes lists what each mode checks.

This program leaks one string per round. Fix it so there’s no leak report.

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const names = [_][]const u8{ "ana", "bo" };
for (names) |n| {
const greeting = try gpa.print("hi {s}", .{n});
std.debug.print("{s}\n", .{greeting});
}
}

Hint: one defer line, inside the loop.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const names = [_][]const u8{ "ana", "bo" };
for (names) |n| {
const greeting = try gpa.print("hi {s}", .{n});
defer gpa.free(greeting);
std.debug.print("{s}\n", .{greeting});
}
}

Output:

hi ana
hi bo

The defer belongs to the loop body, so it frees each greeting at the end of its own round.

makeLabel allocates a label, then returns error.TooLong if the label is over 8 bytes. It leaks on the error. Add the missing line, and write a main that calls it with "box" and "warehouse".

fn makeLabel(gpa: std.mem.Allocator, name: []const u8) ![]u8 {
const label = try gpa.print("[{s}]", .{name});
if (label.len > 8) return error.TooLong;
return label;
}

Hint: errdefer gpa.free(label); right after the allocation.

Show solution
const std = @import("std");
fn makeLabel(gpa: std.mem.Allocator, name: []const u8) ![]u8 {
const label = try gpa.print("[{s}]", .{name});
errdefer gpa.free(label);
if (label.len > 8) return error.TooLong;
return label;
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
for ([_][]const u8{ "box", "warehouse" }) |name| {
const label = makeLabel(gpa, name) catch |err| {
std.debug.print("{s}: {s}\n", .{ name, @errorName(err) });
continue;
};
defer gpa.free(label);
std.debug.print("{s}\n", .{label});
}
}

Output:

[box]
warehouse: TooLong

"[warehouse]" is 11 bytes, so it fails, and errdefer frees it on the way out. No leak report.

Write a test that calls the fixed makeLabel from exercise 2 with std.testing.allocator, checks the result is "[box]", and frees it, so the test passes with no leak.

Hint: defer std.testing.allocator.free(label); and try std.testing.expectEqualStrings("[box]", label);.

Show solution
const std = @import("std");
fn makeLabel(gpa: std.mem.Allocator, name: []const u8) ![]u8 {
const label = try gpa.print("[{s}]", .{name});
errdefer gpa.free(label);
if (label.len > 8) return error.TooLong;
return label;
}
test "makeLabel wraps the name" {
const label = try makeLabel(std.testing.allocator, "box");
defer std.testing.allocator.free(label);
try std.testing.expectEqualStrings("[box]", label);
}

Output:

1/1 main.test.makeLabel wraps the name...OK
All 1 tests passed.

Take out the defer line and run it again: the check still passes, but the run fails with 1 tests leaked memory.

  • A leak is memory you allocated and never freed. It matters most in loops, long-running programs and libraries.
  • In debug builds, init.gpa prints a report for each leak: how many bytes (len) and the stack trace of the allocation.
  • Read the trace down to your own file: that’s where the free is missing.
  • A leak report doesn’t change the exit code, so read the output.
  • Fix most leaks with defer free on the next line, and error-path leaks with errdefer.
  • In tests, std.testing.allocator makes a leaking test fail.

Next up: Zig Lifetimes & Ownership, how long memory stays valid and who is responsible for freeing it.

Quick check

1. A leak report says len: 12 (0xc). What does that tell you?
2. The first line of a leak's stack trace is inside lib/std/mem/Allocator.zig. Where should you look?
3. A function allocates a result, then may return an error before returning it. How do you stop the error path from leaking?
4. A test uses std.testing.allocator and forgets one free. What happens?