Curriculum Memory defer and errdefer exercise 3 · mcq
defer and errdefer
errdefer is defer's twin — same shape, but only fires
when the function returns via an ERROR. The canonical pattern
is "alloc, then errdefer free" — so on success the caller
takes ownership of the alloc; on failure the alloc is
cleaned up. Pick the right shape.
About this theme
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.