Zig Errdefer
You know defer: it runs cleanup when a block ends, no matter how. But some cleanup should only happen when things go wrong. Picture a function that builds something in several steps and hands it to its caller. If every step works, the caller owns the result and will clean it up later. If step three fails, the function must undo steps one and two itself, or that memory leaks. errdefer is made for exactly this, and once you see the pattern you’ll spot it all over the standard library.
errdefer in one example
Section titled “errdefer in one example”errdefer works like defer, with one difference: it only runs when the function is left by returning an error. Here a pretend server starts up in three steps:
const std = @import("std");
fn startServer(fail_at: u8) !void { std.debug.print("1. load config\n", .{}); errdefer std.debug.print(" undo 1: forget config\n", .{});
std.debug.print("2. open log file\n", .{}); errdefer std.debug.print(" undo 2: close log file\n", .{}); if (fail_at == 2) return error.LogFailed;
std.debug.print("3. open network port\n", .{}); if (fail_at == 3) return error.PortInUse;
std.debug.print("server is running\n", .{});}
pub fn main() void { startServer(0) catch {}; std.debug.print("---\n", .{}); startServer(3) catch |err| std.debug.print("failed: {t}\n", .{err});}Output:
1. load config2. open log file3. open network portserver is running---1. load config2. open log file3. open network port undo 2: close log file undo 1: forget configfailed: PortInUseThe first call succeeds, so neither errdefer runs: the server keeps its config and log file. The second call fails at step 3, and both errdefers run, newest first, just like defer. Step 2 is undone before step 1, so things come apart in the reverse order they were put together.
Notice there’s no errdefer after step 3. If step 3 fails, there’s nothing from step 3 to undo. You write an errdefer right after each step that succeeded and will need undoing.
The real job: returning something you built
Section titled “The real job: returning something you built”The most common use is memory. This function makes a Player with two separate allocations: a copy of the name and a list of scores. It returns the player to the caller, who frees both later with destroy:
const std = @import("std");
const Player = struct { name: []u8, scores: []u32,
fn create(gpa: std.mem.Allocator, name: []const u8) !Player { const name_copy = try gpa.dupe(u8, name); errdefer gpa.free(name_copy);
const scores = try gpa.alloc(u32, 10); @memset(scores, 0);
return .{ .name = name_copy, .scores = scores }; }
fn destroy(self: Player, gpa: std.mem.Allocator) void { gpa.free(self.scores); gpa.free(self.name); }};
pub fn main(init: std.process.Init) void { // Works: both allocations succeed. const p = Player.create(init.gpa, "Ada") catch |err| { std.debug.print("create failed: {t}\n", .{err}); return; }; defer p.destroy(init.gpa); std.debug.print("created {s} with {d} scores\n", .{ p.name, p.scores.len });
// Fails: the second allocation (index 1) is made to fail on purpose. var failing = std.testing.FailingAllocator.init(init.gpa, .{ .fail_index = 1 }); if (Player.create(failing.allocator(), "Bob")) |q| { q.destroy(failing.allocator()); } else |err| { std.debug.print("create failed: {t}\n", .{err}); }}Output:
created Ada with 10 scorescreate failed: OutOfMemoryTake create one line at a time:
gpa.dupe(u8, name)allocates a copy of the name. If that fails,tryreturns and there’s nothing to clean up yet.errdefer gpa.free(name_copy);says “if anything after this point fails, free the name”.gpa.alloc(u32, 10)allocates the scores. If this fails,tryreturnserror.OutOfMemory, and theerrdeferfrees the name on the way out.- If both worked,
return .{ ... }hands everything to the caller. That’s a success, so theerrdeferdoes not run, and the caller now owns both pieces.
Running out of memory is hard to make happen on demand, so main uses std.testing.FailingAllocator. It wraps a real allocator and makes one chosen allocation fail: with .fail_index = 1, the first allocation (index 0, the name) works and the second (index 1, the scores) fails. It’s a testing tool, and a very handy one for checking your error paths; Zig Testing Allocator shows more.
Why not defer or nothing at all?
Section titled “Why not defer or nothing at all?”Try the two wrong versions in your head:
- With
defer gpa.free(name_copy);the name is freed every time, also on success. The caller gets aPlayerwhosenamepoints at memory that’s already been given back. Reading it later is a use-after-free bug, the kind that crashes at random or prints garbage. - With nothing, the failure path leaks the name. Delete the
errdeferline and run it again, and the allocator frominit.gpacomplains when the program ends. You’ll see something like:
created Ada with 10 scorescreate failed: OutOfMemoryerror(SafeAllocator): leaked [addr: 7f292e727a58, len: 3 (0x3) align: 1] allocated at:std/mem/Allocator.zig:481:40: 0x10545ce in dupe__func_109 (std.zig) const new_buf = try allocator.alloc(T, m.len); ^main.zig:8:39: 0x11ee7e4 in create (main.zig) const name_copy = try gpa.dupe(u8, name); ^len: 3 is the three bytes of "Bob", and the trace points right at the dupe that was never freed. The address and the lines below change from run to run.
errdefer in a loop
Section titled “errdefer in a loop”What if you build several things in a loop and one in the middle fails? You need to free all the ones made so far, and only those. Keep a count, and let the errdefer loop over that many:
const std = @import("std");
fn makeLabels(gpa: std.mem.Allocator, count: usize) ![][]u8 { const labels = try gpa.alloc([]u8, count); errdefer gpa.free(labels);
var made: usize = 0; errdefer for (labels[0..made]) |label| gpa.free(label);
for (labels, 0..) |*label, i| { label.* = try gpa.print("label {d}", .{i + 1}); made += 1; } return labels;}
fn freeLabels(gpa: std.mem.Allocator, labels: [][]u8) void { for (labels) |label| gpa.free(label); gpa.free(labels);}
pub fn main(init: std.process.Init) void { const labels = makeLabels(init.gpa, 3) catch return; defer freeLabels(init.gpa, labels); for (labels) |label| std.debug.print("{s}\n", .{label});
// Allocation number 3 (index 2) fails: two labels are already made. var failing = std.testing.FailingAllocator.init(init.gpa, .{ .fail_index = 2 }); if (makeLabels(failing.allocator(), 3)) |more| { freeLabels(failing.allocator(), more); } else |err| { std.debug.print("makeLabels failed: {t}\n", .{err}); }}Output:
label 1label 2label 3makeLabels failed: OutOfMemorygpa.print(...) formats text into newly allocated memory (see Zig Format Strings). In the failing run, allocation 0 is the labels list, allocation 1 is "label 1", and allocation 2, "label 2", fails. At that moment made is 1, so the second errdefer frees exactly one label, then the first errdefer frees the list. No leak, and nothing freed twice.
This works because an errdefer reads variables when it runs, not when it’s written (same as defer). By the time it runs, made holds the real count.
It only counts errors that leave the function
Section titled “It only counts errors that leave the function”An errdefer runs when its block is left because the function is returning an error. Two cases surprise people:
const std = @import("std");
fn steps() !void { { errdefer std.debug.print("inner errdefer\n", .{}); std.debug.print("inner block finished fine\n", .{}); } errdefer std.debug.print("outer errdefer\n", .{}); return error.LateFailure;}
fn handlesItsOwnError() !void { errdefer std.debug.print("this never prints\n", .{}); const n = std.fmt.parseInt(u8, "oops", 10) catch 0; std.debug.print("parsed with a fallback: {d}\n", .{n});}
pub fn main() void { steps() catch {}; handlesItsOwnError() catch {};}Output:
inner block finished fineouter errdeferparsed with a fallback: 0- The inner
errdefernever runs. Its block ended normally, so it was done and gone before the function failed later. - In
handlesItsOwnError,parseIntfails, butcatch 0handles it right there. The function itself returns successfully, so itserrdeferstays quiet.
Also, errdefer is only about errors. Returning null from a function that returns !?T is a success, and so is a normal return. A panic doesn’t run it either, because a panic stops the program.
The errdefer |err| capture is gone
Section titled “The errdefer |err| capture is gone”Older Zig code, and some tutorials, write errdefer |err| to see which error is being returned, usually to log it. That was removed in Zig 0.17, and now it’s a syntax error:
const std = @import("std");
fn connect(host: []const u8) !void { errdefer |err| std.debug.print("connect failed: {t}\n", .{err}); if (host.len == 0) return error.NoHost;}
pub fn main() void { connect("") catch {};}main.zig:4:14: error: expected block or expression, found '|' errdefer |err| std.debug.print("connect failed: {t}\n", .{err}); ^The 0.17.0 release notes suggest splitting the function in two: the inner one does the work, and the outer one catches the error, does what it needs with it, and passes it on:
const std = @import("std");
fn connect(host: []const u8) !void { if (host.len == 0) return error.NoHost; std.debug.print("connected to {s}\n", .{host});}
fn connectLogged(host: []const u8) !void { connect(host) catch |err| { std.debug.print("connect failed: {t}\n", .{err}); return err; };}
pub fn main() void { connectLogged("example.org") catch {}; connectLogged("") catch {};}Output:
connected to example.orgconnect failed: NoHostIt’s a few more lines, but it’s plain catch, and the caller still gets the original error. Keep using plain errdefer (without a capture) for cleanup: that hasn’t changed.
Practice
Section titled “Practice”1. Undo in the right order
Section titled “1. Undo in the right order”Write fn bake(fail_at: u8) !void with four steps: “heat oven”, “mix dough”, “fill tray”, “bake”. Add an errdefer after each of the first three that prints how to undo it (“turn oven off”, “throw dough away”, “empty tray”). Make step 4 fail when fail_at == 4 and step 2 fail when fail_at == 2. Call it with 4, then with 2.
Hint: a step that fails shouldn’t have its own errdefer run, so check fail_at before writing that step’s errdefer.
Show solution
const std = @import("std");
fn bake(fail_at: u8) !void { std.debug.print("heat oven\n", .{}); errdefer std.debug.print(" turn oven off\n", .{});
if (fail_at == 2) return error.NoFlour; std.debug.print("mix dough\n", .{}); errdefer std.debug.print(" throw dough away\n", .{});
std.debug.print("fill tray\n", .{}); errdefer std.debug.print(" empty tray\n", .{});
if (fail_at == 4) return error.OvenBroke; std.debug.print("bake\n", .{});}
pub fn main() void { bake(4) catch |err| std.debug.print("failed: {t}\n", .{err}); std.debug.print("---\n", .{}); bake(2) catch |err| std.debug.print("failed: {t}\n", .{err});}Output:
heat ovenmix doughfill tray empty tray throw dough away turn oven offfailed: OvenBroke---heat oven turn oven offfailed: NoFlourWhen step 2 fails, only the oven’s errdefer had been reached, so only that one runs. An errdefer the code never got to is never scheduled.
2. A pair of buffers
Section titled “2. A pair of buffers”Write fn makePair(gpa: std.mem.Allocator) !struct { a: []u8, b: []u8 } that allocates two 4-byte buffers and returns both. Use errdefer so that nothing leaks if the second allocation fails. Test it with a FailingAllocator set to .fail_index = 1 and print the error.
Hint: only the first buffer needs an errdefer. After the second allocation there’s nothing left that can fail.
Show solution
const std = @import("std");
const Pair = struct { a: []u8, b: []u8 };
fn makePair(gpa: std.mem.Allocator) !Pair { const a = try gpa.alloc(u8, 4); errdefer gpa.free(a); const b = try gpa.alloc(u8, 4); return .{ .a = a, .b = b };}
pub fn main(init: std.process.Init) void { var failing = std.testing.FailingAllocator.init(init.gpa, .{ .fail_index = 1 }); const gpa = failing.allocator(); if (makePair(gpa)) |pair| { gpa.free(pair.a); gpa.free(pair.b); std.debug.print("got a pair\n", .{}); } else |err| { std.debug.print("makePair failed: {t}\n", .{err}); }}Output:
makePair failed: OutOfMemoryThe program ends without a leak report, which proves the errdefer freed a. Try deleting the errdefer line: the allocator from init.gpa then reports a 4-byte leak. Giving the struct a name (Pair) makes the return type easier to read than an anonymous struct { ... }.
errdeferruns cleanup only when the function returns an error. On success it’s skipped.- Use it when a function builds something for its caller: free the pieces if a later step fails.
deferwhen this function always frees it;errdeferwhen the caller frees it on success.- Several
errdefers run newest first, undoing steps in reverse order. - In a loop, keep a count of what’s been made and free exactly that many in the
errdefer. - An error that’s handled inside the function, or a block that ended normally, doesn’t trigger it.
errdefer |err|was removed in 0.17: catch the error in a small wrapper function instead.
Next up: Zig Optionals, for values that might simply not be there.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: errdefer: the official rules and examples.
- Zig 0.17.0 release notes: errdefer capture removed: why
|err|went away and how to migrate. - Zig language reference: defer: the always-runs version, for comparison.
- Zig in-depth overview: how Zig manages resources without a garbage collector.