Curriculum Memory defer and errdefer
defer and errdefer
defer is Zig's structural cleanup tool: each defer statement runs when the enclosing block exits, in LIFO order. errdefer is the same idea, but it only fires when the function returns via an error path. The canonical pattern is alloc-then-defer-free (always run cleanup) or alloc-then-errdefer-free (only on the error path, so successful returns hand ownership to the caller). Once these two land in your fingertips, manual memory management stops being scary.
Exercises
9 ready
01
pick one
TypeScript reaches for try { ... } finally { ... } for
02
pick one
Multiple defer statements in the same block run in REVERSE
03
pick one
errdefer is defer's twin — same shape, but only fires
04
fill blanks
Fill the missing keyword. The line schedules a cleanup that
05
fill blanks
Fill the missing keyword. Same as defer, but fires ONLY
06
type one line
Type the missing Zig line — schedule the buffer's release so
07
type one line
Type the missing Zig line — schedule cleanup that runs ONLY
08
write a program
Write a complete Zig program that demonstrates defer's
09
write a program
Write a complete Zig program that: