Commit eb1e6fbd
eb1e6fbd518cMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified
Description
fix(strscan): peek caches buffer instead of leaking per call (#813)
Each StringScanner#peek(n) call malloc'd a fresh buffer and returned it -- with no destructor pairing, every peek leaked. A peek loop (e.g. for tokenizer lookahead) bloated heap linearly.
Add sc->peek_buf + sc->peek_buf_cap to the struct, grow on demand, and overwrite-then-return. Subsequent peek() calls reuse the same buffer; n that fits the existing cap is constant-time.
Also NULL-guard sc and clamp negative n to 0.
Closes #813
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- eb1e6fbd518c
- Parent
- 0aede4be4b0b
lib/strscan.cmodifiedView file
@@ -20,6 +20,10 @@
2020
int64_t last_pos; /* position before last scan (for unscan) */2121
char *matched; /* last matched string (heap-allocated) */2222
int64_t matched_len;23+
/* Issue #813: cache the peek buffer so repeated peek() calls24+
don't leak. Reallocated on demand when n grows. */25+
char *peek_buf;26+
int64_t peek_buf_cap;2327
} sp_StringScanner;2428
2529
/* Constructor.@@ -153,15 +157,26 @@
153157
return sc->matched;154158
}155159
156-
/* peek(n) — look ahead n characters without advancing */160+
/* peek(n) — look ahead n characters without advancing.161+
Issue #813: reuse the cached peek buffer across calls so a162+
tight peek() loop doesn't leak one heap allocation per call.163+
Grow the cap on demand. */157164
const char *sp_StringScanner_peek(sp_StringScanner *sc, int64_t n) {158-
if (sc->pos >= sc->source_len) return "";165+
if (!sc || sc->pos >= sc->source_len) return "";159166
int64_t remaining = sc->source_len - sc->pos;160167
if (n > remaining) n = remaining;161-
char *buf = (char *)malloc(n + 1);162-
memcpy(buf, sc->source + sc->pos, n);163-
buf[n] = '\0';164-
return buf;168+
if (n < 0) n = 0;169+
if (n + 1 > sc->peek_buf_cap) {170+
int64_t nc = sc->peek_buf_cap ? sc->peek_buf_cap : 16;171+
while (nc < n + 1) nc *= 2;172+
char *nb = (char *)realloc(sc->peek_buf, (size_t)nc);173+
if (!nb) return "";174+
sc->peek_buf = nb;175+
sc->peek_buf_cap = nc;176+
}177+
memcpy(sc->peek_buf, sc->source + sc->pos, n);178+
sc->peek_buf[n] = '\0';179+
return sc->peek_buf;165180
}166181
167182
/* unscan — revert to position before last scan */