szn

Bug 395 — Pty.spawn

395. Pty.spawn: #267’s errdefer and defer both free szn_env_z/szn_pane_z/cwd_z — double-free on fork() failure

Severity: CRITICAL Status: ✅ RESOLVED

The #267 fix registered an errdefer (pty.zig:169-173) freeing cwd_z, szn_pane_z, szn_env_z, then added a defer block with the identical frees for the success path (:179-183). Zig runs both on any error return after :183 — including the immediate if (pid < 0) return error.ForkFailed; (:186). On fork failure (fd/pid pressure) every buffer is freed twice through the server’s global GPA: heap corruption.

const szn_env_z = try allocator.dupeZ(u8, szn_env);
const szn_pane_z = try allocator.dupeZ(u8, szn_pane); // fails -> szn_env_z leaks (:165 uncovered)
var cwd_z: ?[:0]const u8 = null;
errdefer { if (cwd_z) |c| allocator.free(c); allocator.free(szn_pane_z); allocator.free(szn_env_z); }
...
defer { if (cwd_z) |c| allocator.free(c); allocator.free(szn_pane_z); allocator.free(szn_env_z); }
const pid = fork();
if (pid < 0) return error.ForkFailed;                 // defer + errdefer both fire

Secondary: szn_env_z is not covered by any errdefer if the szn_pane_z dupe at :166 fails (the errdefer is registered at :169, after both dupes; only argv is protected at :154).

Fix: single ownership pattern — free on the error path only (explicit catch frees + errdefer), never stack defer and errdefer over the same pointers; register the errdefer immediately after each dupe.