In Zig, defer schedules an expression or block to run when its enclosing scope exits—on return, error propagation with try, or the end of a block. section 3.4.2
Use defer to keep cleanup reliable and close to the resource it protects:
- Free allocated memory with defer so it is released even if a later operation fails. section 3.4.2
- Use errdefer for cleanup that should run only when an error is returned; defer and errdefer can both take a block. section 3.4.2
for (args[1..]) |filepath| {
const text = try cwd.readFileAlloc(
init.gpa,
filepath,
io,
.unlimited,
);
defer init.gpa.free(text);
try stdout.writeAll(text);
}
In this cat loop, each file buffer is freed when the loop body’s scope exits, including if writing to stdout fails. section 3.4.2



