Skip to content

Fix use-after-free bug in postgres example (14-02.zig)#127

Draft
jiacai2050 with Copilot wants to merge 2 commits into
mainfrom
copilot/fix-examples-job-macos-latest
Draft

Fix use-after-free bug in postgres example (14-02.zig)#127
jiacai2050 with Copilot wants to merge 2 commits into
mainfrom
copilot/fix-examples-job-macos-latest

Conversation

Copilot AI commented Jul 16, 2026

Copy link
Copy Markdown

The examples (macos-latest) CI job was failing in run exe examples-14-02 with ERROR: invalid input syntax for type integer: "" because color_id held a dangling pointer into a freed PGresult buffer.

Root cause

color_id was extracted via std.mem.span(c.PQgetvalue(res, 0, 0)) inside a blk: block that also had defer c.PQclear(res). The defer fires when the block exits — including on break :blk — so by the time color_id was used in the inner loop, the PGresult buffer it pointed into was already freed. On macOS, freed memory is zeroed, so color_id read as "", and PostgreSQL rejected it as an invalid integer.

Fix

Remove the blk: scope. Execute PQexecPrepared for insert_cat_colors directly in the outer inline for body and defer PQclear(color_res) there, so color_id stays valid for the full duration of the inner loop.

// Before: PQclear fires at break :blk, before color_id is used
const color_id = blk: {
    const res = c.PQexecPrepared(...);
    defer c.PQclear(res);           // ← fires here, freeing res's buffer
    ...
    break :blk std.mem.span(c.PQgetvalue(res, 0, 0));
};
// color_id is now a dangling pointer

// After: PQclear deferred to outer loop scope
const color_res = c.PQexecPrepared(...);
defer c.PQclear(color_res);         // ← fires at end of inline for iteration
const color_id = std.mem.span(c.PQgetvalue(color_res, 0, 0));
// color_id remains valid through the inner loop

The `color_id` slice pointed into PGresult memory that was freed
by `defer c.PQclear(res)` when the `blk:` block exited via `break`.
On macOS the freed memory is zeroed, causing an empty string to be
passed as `color_id` to the next PQexecPrepared call, which then
failed with "invalid input syntax for type integer: ''".

Fix: remove the blk: scope and defer PQclear(color_res) at the
outer inline for loop level, so color_id stays valid for the inner
loop that uses it.
Copilot AI changed the title [WIP] Fix failing GitHub Actions job examples (macos-latest) Fix use-after-free bug in postgres example (14-02.zig) Jul 16, 2026
Copilot AI requested a review from jiacai2050 July 16, 2026 04:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants