Commit c24ef98f

c24ef98fd187Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

fix(stringio): sio_grow + set_string realloc check (#818)

Two realloc sites in lib/stringio.c assigned the result directly back to sio->buf, so an OOM failure used to NULL out the buffer (leaking the old one and crashing subsequent reads):

  • sio_grow (the per-write growth hook).
  • sp_StringIO_set_string (the string= assignment).

Capture realloc into a temp; on NULL, leave the existing buffer intact and return. Writers then either hit the existing-cap path or run out of room and truncate; reads keep working against the still-valid buf.

Closes #818

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
c24ef98fd187
Parent
a6e7e7f0e211

lib/stringio.cmodifiedView file

@@ -22,13 +22,20 @@
2222 int closed; /* 1 if closed */
2323 } sp_StringIO;
2424
25-/* Internal: ensure buffer has room for `need` more bytes */
25+/* Internal: ensure buffer has room for `need` more bytes.
26+ Issue #818: capture realloc into a temp and only commit on success
27+ so an OOM failure doesn't NULL out sio->buf (leaking the old buf
28+ and crashing subsequent reads). On failure leave the buffer alone
29+ and let the caller's bounds check truncate the write. */
2630 static void sio_grow(sp_StringIO *sio, int64_t need) {
31+ if (!sio) return;
2732 int64_t required = sio->pos + need;
2833 if (required <= sio->cap) return;
2934 int64_t new_cap = sio->cap ? sio->cap : 64;
3035 while (new_cap < required) new_cap *= 2;
31- sio->buf = (char *)realloc(sio->buf, new_cap + 1);
36+ char *nb = (char *)realloc(sio->buf, new_cap + 1);
37+ if (!nb) return;
38+ sio->buf = nb;
3239 sio->cap = new_cap;
3340 }
3441
@@ -282,10 +289,13 @@
282289
283290 /* string= — replace buffer contents */
284291 void sp_StringIO_set_string(sp_StringIO *sio, const char *str) {
292+ if (!sio || !str) return;
285293 int64_t len = (int64_t)strlen(str);
286294 if (len > sio->cap) {
295+ char *nb = (char *)realloc(sio->buf, len + 1);
296+ if (!nb) return;
297+ sio->buf = nb;
287298 sio->cap = len;
288- sio->buf = (char *)realloc(sio->buf, sio->cap + 1);
289299 }
290300 memcpy(sio->buf, str, len);
291301 sio->buf[len] = '\0';