Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Control Flow and Functions

defer and errdefer

Learn Zig's defer and errdefer: run cleanup when a scope ends, execution order, pairing allocation with free, errdefer on failure, defer in loops and blocks, and common pitfalls.

In a language without garbage collection and without destructors, cleanup is your job. C programmers write goto cleanup; labels or deeply nested if blocks. Zig gives you a one-word solution: defer schedules a statement to run when the current scope ends, no matter how it ends. Put the cleanup right next to the acquisition and you can no longer forget it.

defer

ZIG
const std = @import("std");

pub fn main() void {
    std.debug.print("start\n", .{});
    defer std.debug.print("cleanup\n", .{});
    std.debug.print("working\n", .{});
}
TEXT
start
working
cleanup

The deferred statement runs when the enclosing block exits: end of the function, an early return, a break out of a loop, even propagating an error. Its natural home is resource management:

ZIG
const file = try std.fs.cwd().openFile("data.txt", .{});
defer file.close();
// ... use file; it is closed on every path out of this scope ...

The defer sits directly under the line that opened the file, so a reader can verify at a glance that nothing leaks.

Order: last in, first out

Multiple defers run in reverse order, like a stack. This matches resource dependencies: what you acquired last is released first.

ZIG
pub fn main() void {
    defer std.debug.print("1 (registered first, runs last)\n", .{});
    defer std.debug.print("2\n", .{});
    defer std.debug.print("3 (registered last, runs first)\n", .{});
    std.debug.print("body\n", .{});
}
TEXT
body
3 (registered last, runs first)
2
1 (registered first, runs last)

defer runs at scope exit

Acquire Open a file, allocate memory, lock a mutex
Defer the release Write defer on the very next line
Any exit path return, break, error or end of block
Reverse order Last registered runs first

Cleanup is next to the code it cleans up.

1 / 2

Scope is the block, not the function

defer belongs to the nearest enclosing block, so a defer inside a loop body runs at the end of every iteration:

ZIG
for (0..3) |i| {
    std.debug.print("start {d}\n", .{i});
    defer std.debug.print("end {d}\n", .{i});
}
TEXT
start 0
end 0
start 1
end 1
start 2
end 2

This is exactly what you want for per-iteration allocations. Use a bare block { ... } to limit the lifetime of a resource inside a bigger function.

errdefer

errdefer is like defer, but it only runs when the scope is left by returning an error. It is made for cleaning up partially built results: if everything succeeds, ownership moves to the caller and nothing should be freed.

ZIG
fn makeBuffer(allocator: std.mem.Allocator, size: usize) ![]u8 {
    const buffer = try allocator.alloc(u8, size);
    errdefer allocator.free(buffer);          // runs only if we fail below

    try fill(buffer);                          // might return an error
    return buffer;                             // success: caller owns it now
}

Without errdefer the allocation leaks whenever fill fails. With plain defer it would be freed on success too, handing the caller a dangling slice. errdefer is the correct tool.

You may capture the error: errdefer |err| std.debug.print("failed: {s}\n", .{@errorName(err)});.

errdefer and defer can be combined in one function, each guarding one resource:

ZIG
fn openAndRead(allocator: std.mem.Allocator, path: []const u8) ![]u8 {
    const file = try std.fs.cwd().openFile(path, .{});
    defer file.close();                        // always close

    const data = try allocator.alloc(u8, 1024);
    errdefer allocator.free(data);             // free only on error

    const n = try file.readAll(data);
    return data[0..n];
}

(When returning a sub-slice like data[0..n], remember the caller must free the original allocation; real code often returns an owned copy or the full buffer.)

What you cannot do in a defer

A deferred expression cannot use return or try to leave the function, because the function is already finishing. So deferred cleanup must not fail loudly:

ZIG
defer file.close();            // close() returns void: fine
// defer try something();      // error: cannot return from defer expression

If cleanup can fail, handle the error inside the defer with catch (print it, or ignore it deliberately).

defer and returned values

The return expression is evaluated before deferred statements run. That is why returning a value computed from something you free in a defer is a bug:

ZIG
fn bad(allocator: std.mem.Allocator) ![]u8 {
    const buf = try allocator.alloc(u8, 16);
    defer allocator.free(buf);
    return buf;                // returns a slice that is freed immediately
}

The deferred free runs at the end, after the return value (a slice of buf) was already captured, so the caller receives freed memory. Use errdefer here.

Common patterns

  • Allocation then defer allocator.free(x).
  • Open file then defer file.close().
  • Lock a mutex then defer mutex.unlock().
  • Create a growable list then defer list.deinit(allocator); (in 0.15, var list: std.ArrayList(u8) = .empty;; older versions used .init(allocator) and list.deinit()).
  • Restore state: save a flag, defer flag = saved;.

Stand-ins you can run

C has no defer, so cleanup is written by hand with goto. The stand-in mimics defer and errdefer with explicit cleanup labels, printing the same sequence as the Zig examples.

C Stand-in (C): defer and errdefer with goto cleanup labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rust cleans up automatically with Drop, running in reverse declaration order just like defer:

Rust Stand-in (Rust): reverse-order cleanup with Drop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a deferred statement run?

    defer runs at scope exit whether the scope ends normally, by return, by break or by an error.
  2. 2. In what order do several defers in one block run?

    Defers form a stack, so the most recent one runs first.
  3. 3. When does errdefer run?

    errdefer is for cleaning up partial work when a function fails.
  4. 4. Why is defer allocator.free(buf); return buf; a bug?

    The deferred free runs when the function exits, so the returned slice points to freed memory.
  5. 5. A defer is inside a for loop body. How often does it run?

    The scope of the defer is the loop body block, which ends every iteration.

Summary

  • defer stmt; runs stmt when the current block exits, on every path, in reverse order of registration.
  • Put defer directly after acquiring a resource so cleanup cannot be forgotten.
  • errdefer runs only when the scope exits with an error; use it for ownership that transfers on success.
  • A defer inside a loop runs every iteration; deferred code cannot return or try.
  • Never defer-free something you return to the caller.

Next: Pointers