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.
Does a leak even matter?
Section titled “Does a leak even matter?”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.
Your first leak report
Section titled “Your first leak report”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: Ziggyerror(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 ininit.gpa(aSafeAllocatorindebugbuilds) found memory that was never freed.len: 12 (0xc): how many bytes leaked. 3u32s are 12 bytes. The second report’slen: 5is 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.
Fixing it: free on the next line
Section titled “Fixing it: free on the next line”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: ZiggyNo report means no leaks. That silence is what you’re aiming for.
Leak number one: a loop that allocates
Section titled “Leak number one: a loop that allocates”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 0line 1line 2error(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 0line 1line 2Leak number two: the error path
Section titled “Leak number two: the error path”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: okforty: NotANumber7: okerror(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: okforty: NotANumber7: okOne 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.
Other ways to leak
Section titled “Other ways to leak”A few more patterns that show up in leak reports:
- Losing the only pointer.
buf = try gpa.alloc(u8, 100);and laterbuf = 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 userealloc. - 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 adeinitthat frees what it owns. Zig Lifetimes & Ownership shows this pattern. - Forgetting
deiniton a collection. AnArrayListorHashMapallocates as it grows. Writedefer 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.
Leaks in tests
Section titled “Leaks in tests”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.
Leak checks only run in debug and safe
Section titled “Leak checks only run in debug and safe”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.
Practice
Section titled “Practice”1. Plug the loop
Section titled “1. Plug the loop”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 anahi boThe defer belongs to the loop body, so it frees each greeting at the end of its own round.
2. Plug the error path
Section titled “2. Plug the error path”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.
3. Let a test catch it
Section titled “3. Let a test catch it”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...OKAll 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
debugbuilds,init.gpaprints 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
freeis missing. - A leak report doesn’t change the exit code, so read the output.
- Fix most leaks with
defer freeon the next line, and error-path leaks witherrdefer. - In tests,
std.testing.allocatormakes a leaking test fail.
Next up: Zig Lifetimes & Ownership, how long memory stays valid and who is responsible for freeing it.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Report Memory Leaks: how the test runner reports leaks from
std.testing.allocator. - Zig 0.17.0 release notes: SafeAllocator Introduced: what the allocator behind
init.gpachecks in 0.17. - SafeAllocator source (0.17.1): the doc comment at the top lists its guarantees.
- Zig language reference: errdefer: cleanup that only runs on the error path.