[Bug #22384] Fix memory leak on compile error in a later branch of an alternation

This commit is contained in:
Sethu 2026-09-25 14:40:12 +09:30 committed by Nobuyoshi Nakada
parent 2ba68b8c08
commit bf937bfa16
Notes: git 2026-09-30 05:23:37 +00:00
2 changed files with 19 additions and 0 deletions

View File

@ -6759,6 +6759,8 @@ parse_subexp(Node** top, OnigToken* tok, int term,
}
r = parse_branch(&node, tok, term, src, end, env);
if (r < 0) {
/* the failed branch is not linked into topnode yet: free both */
onig_node_free(node);
onig_node_free(topnode);
return r;
}

View File

@ -1004,6 +1004,23 @@ class TestRegexp < Test::Unit::TestCase
assert_equal('foobazquux/foobazquux', result, bug8856)
end
def test_alternation_compile_error_no_memory_leak
# A compile error in the 2nd+ branch of a top-level alternation leaked the
# partially parsed branch (parse_subexp freed the alternation list but not
# the node parse_branch had built so far). Regexp#to_s reaches this path
# for every /(?:a|b)c(d)/-shaped regexp.
assert_no_memory_leak([], "#{<<~"begin;"}", "#{<<~"end;"}", "[Bug #22384]", rss: true)
code = proc do
Regexp.new("a|b(c") rescue nil
/(?:a|b)c(d)/.to_s
end
1_000.times(&code)
begin;
300_000.times(&code)
end;
end
def test_regsub_no_memory_leak
assert_no_memory_leak([], "#{<<~"begin;"}", "#{<<~"end;"}", rss: true)
code = proc do