Commit 92cb004b
92cb004b9061Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified
Description
fix(regexp): named-capture table owns its name strings (#823)
cap_name in the named-capture table pointed directly into the regex source string. When the source came from strip_extended (the x-mode whitespace-stripper), c->stripped was freed at re_compile exit -- leaving every name in pat->named_captures dangling.
Allocate a fresh copy at register time so the table owns its name buffers. Pair with the free loop in re_free so the per-name buffers get released when the pattern is destroyed.
Closes #823
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- 92cb004b9061
- Parent
- 3b84af9f4ffb
lib/regexp/re_compile.cmodifiedView file
@@ -538,9 +538,18 @@
538538
emit(c, RE_SAVE, 0, group * 2);539539
if (cap_name) {540540
/* register named capture */541+
/* Issue #823: cap_name points into the pattern source --542+
but when the pattern came from strip_extended, c->stripped543+
is freed at re_compile exit, leaving the name dangling.544+
Allocate a fresh copy so the named-capture table owns545+
its strings. */546+
char *name_copy = (char*)malloc(cap_name_len + 1);547+
if (!name_copy) compile_error(c, "out of memory");548+
memcpy(name_copy, cap_name, cap_name_len);549+
name_copy[cap_name_len] = '\0';541550
c->named_captures = (re_named_capture*)realloc(c->named_captures,542551
sizeof(re_named_capture) * (c->num_named + 1));543-
c->named_captures[c->num_named].name = cap_name;552+
c->named_captures[c->num_named].name = name_copy;544553
c->named_captures[c->num_named].name_len = cap_name_len;545554
c->named_captures[c->num_named].group = group;546555
c->num_named++;@@ -1058,7 +1067,16 @@
10581067
}10591068
free(pat->classes);10601069
}1061-
free(pat->named_captures);1070+
/* Issue #823: per-name buffers now owned by the table; free each1071+
before freeing the array itself. Names registered before the1072+
fix were uninit memory pointers but the new allocator path1073+
gives us our own copy. */1074+
if (pat->named_captures) {1075+
for (uint16_t i = 0; i < pat->num_named; i++) {1076+
free((void *)pat->named_captures[i].name);1077+
}1078+
free(pat->named_captures);1079+
}10621080
free(pat->prefix);10631081
free(pat->cached_visited);10641082
free(pat->cached_threads[0]);