TExcelTAD
Home › Zig › Zig defer & errdefer

Zig defer & errdefer

Programs that manage resources — memory, files, locks — must clean them up on every path out of a function, including early returns and errors. Forgetting one path is a classic source of leaks. Zig solves this with defer: write the cleanup right next to the acquisition, and Zig runs it automatically when the scope ends.

defer

A defer statement schedules code to run when the current block exits, no matter how it exits:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    std.debug.print("open file\n", .{});
    defer std.debug.print("close file\n", .{});

    std.debug.print("read data\n", .{});
    std.debug.print("process data\n", .{});
}
open file
read data
process data
close file

Reverse order

Several defers in one scope run in reverse order — last registered, first executed. That is exactly what you want: resources are released in the opposite order they were acquired.

zig · try it yourself
const std = @import("std");

pub fn main() void {
    std.debug.print("connect database\n", .{});
    defer std.debug.print("disconnect database\n", .{});

    std.debug.print("begin transaction\n", .{});
    defer std.debug.print("end transaction\n", .{});

    std.debug.print("lock table\n", .{});
    defer std.debug.print("unlock table\n", .{});

    std.debug.print("-- work --\n", .{});
}
connect database
begin transaction
lock table
-- work --
unlock table
end transaction
disconnect database

Block scope, not function scope

Unlike Go, Zig's defer belongs to the enclosing block, not the whole function. In a loop, it runs at the end of each iteration:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    for (1..4) |i| {
        std.debug.print("start {d}\n", .{i});
        defer std.debug.print("  cleanup {d}\n", .{i});
        if (i == 2) continue; // cleanup still runs
        std.debug.print("  work {d}\n", .{i});
    }
    std.debug.print("after loop\n", .{});
}
start 1
  work 1
  cleanup 1
start 2
  cleanup 2
start 3
  work 3
  cleanup 3
after loop

A deferred block may contain several statements: defer { a(); b(); }. It may not contain return or try, since cleanup must not change the function's outcome.

errdefer

errdefer runs only if the scope is left by returning an error. It is the tool for undoing partial work when a later step fails:

zig · try it yourself
const std = @import("std");

var reserved: u32 = 0;

fn reserveSeats(count: u32, fail_payment: bool) !void {
    reserved += count;
    std.debug.print("reserved {d} seats\n", .{count});
    errdefer {
        reserved -= count;
        std.debug.print("rolled back {d} seats\n", .{count});
    }

    if (fail_payment) return error.PaymentDeclined;
    std.debug.print("payment ok\n", .{});
}

pub fn main() void {
    reserveSeats(2, false) catch {};
    reserveSeats(5, true) catch |err| std.debug.print("error: {t}\n", .{err});
    std.debug.print("seats reserved in total: {d}\n", .{reserved});
}
reserved 2 seats
payment ok
reserved 5 seats
rolled back 5 seats
error: PaymentDeclined
seats reserved in total: 2

On the successful call the errdefer did nothing; on the failing call it undid the reservation.

The allocation pattern

You will see this shape constantly in real Zig code once you start using allocators:

zig
fn makeBuffers(allocator: std.mem.Allocator) !Buffers {
    const a = try allocator.alloc(u8, 1024);
    errdefer allocator.free(a);      // if the next line fails, free a

    const b = try allocator.alloc(u8, 4096);
    errdefer allocator.free(b);

    return .{ .a = a, .b = b };      // success: the caller now owns both
}

// caller:
const bufs = try makeBuffers(allocator);
defer bufs.deinit(allocator);         // always freed when the caller is done

errdefer handles "I'm giving up halfway", defer handles "I'm done with it".

Capturing the error in errdefer

errdefer |err| … gives you the error that is being returned — handy for logging:

zig
errdefer |err| std.log.err("setup failed: {t}", .{err});

Summary

Statement Runs when the scope exits…
defer x; always (normal end, return, break, continue, error)
errdefer x; only when returning an error
errdefer |e| x; only on error, with the error captured

Tip: Make it a reflex: every time you write a line that acquires something, the very next line should be the matching defer or errdefer.

Test yourself

In what order do three defer statements in the same block run?

  1. In the order written
  2. In reverse order
  3. In random order
  4. Only the last one runs

When does errdefer code run?

  1. Always
  2. Only if the scope exits by returning an error
  3. Only when the program crashes
  4. At program start

A defer inside a for loop body runs …

  1. once, when the function returns
  2. at the end of each iteration
  3. never
  4. before each iteration