szn

Bug 357 — cmdLoadBuffer invalid free of static pointer with stale capacity

357. Every successful load-buffer performs an invalid free

File: src/cmd/cmd.zig:524-537 Severity: CRITICAL Status: ✅ FIXED

Fix (applied)

The new regression test immediately exposed a second half of this bug: pushOwned(data.items) handed the buffer stack a sub-span of a larger capacity allocation; BufferEntry.deinit later frees by .len, which fails the DebugAllocator canary check (“Invalid free”) even before the static-pointer deferred deinit fired.

cmdLoadBuffer now uses data.toOwnedSlice() so the stack receives an exactly-sized allocation, with errdefers covering name/data on every failure path after ownership starts transferring.

Test: load-buffer transfers ownership without invalid free — bug #357 (real temp file, full parse → exec → server.deinit cycle under testing.allocator’s ownership checks).

Problem

loadb <file> succeeds functionally but its cleanup path frees memory that was never heap-allocated with a length that was never allocated — DebugAllocator asserts / crashes; libc malloc corrupts the heap.

Root Cause

var data: std.ArrayList(u8) = .empty;
defer data.deinit(server.allocator);      // ① deferred free
...
server.buffers.pushOwned(name, data.items) catch return .err;
data.items = &.{};                        // ② ptr → comptime static, capacity kept
return .ok;

In Zig 0.16 unmanaged deinit executes gpa.free(self.items.ptr[0..self.capacity]). After line ② items.ptr points at static storage while capacity retains the ≥4096 value from the appends, so ① frees a non-heap pointer with a bogus span. No test covers this path (only table lookup("load-buffer")).

Fix (proposed)

Replace data.items = &.{}; with data = .empty; (resets ptr and capacity), or drop the defer once ownership has transferred and document it. Regression test: run cmdLoadBuffer against a temp file under testing.allocator and verify leak-check passes.