Commit a6e7e7f0
a6e7e7f0e211Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified
Description
fix(stringio): NULL-check calloc/malloc in sp_StringIO_new (#817)
sp_StringIO_new and sp_StringIO_new_s used to dereference the calloc/malloc results directly. On OOM the next line crashed.
Add explicit NULL checks; on failure, free any partially-allocated state and return NULL. The existing callers null-check sio->buf (via the ternary in sp_StringIO_string), so a NULL return surfaces as an empty StringIO rather than a SEGV.
Also guard sp_StringIO_new_s against a NULL initial string -- a few call sites coerce nil through this path.
Closes #817
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- a6e7e7f0e211
- Parent
- b2c7206f6a87
lib/stringio.cmodifiedView file
@@ -47,18 +47,26 @@
4747
}4848
4949
/* Constructor: StringIO.new or StringIO.new("initial") */50+
/* Issue #817: check calloc returns before dereferencing. On OOM, free51+
the partially allocated state and return NULL; callers already null-52+
check sio->buf via the ternary in sp_StringIO_string. */5053
sp_StringIO *sp_StringIO_new(void) {5154
sp_StringIO *sio = (sp_StringIO *)calloc(1, sizeof(sp_StringIO));55+
if (!sio) return NULL;5256
sio->buf = (char *)calloc(1, 64);57+
if (!sio->buf) { free(sio); return NULL; }5358
sio->cap = 63;5459
return sio;5560
}5661
5762
sp_StringIO *sp_StringIO_new_s(const char *initial) {63+
if (!initial) initial = "";5864
sp_StringIO *sio = (sp_StringIO *)calloc(1, sizeof(sp_StringIO));65+
if (!sio) return NULL;5966
int64_t len = (int64_t)strlen(initial);6067
int64_t cap = len < 63 ? 63 : len;6168
sio->buf = (char *)malloc(cap + 1);69+
if (!sio->buf) { free(sio); return NULL; }6270
memcpy(sio->buf, initial, len);6371
sio->buf[len] = '\0';6472
sio->len = len;