From 064d49a7f04a6947de5fdc4f4dcb9ea3ceaf2191 Mon Sep 17 00:00:00 2001 From: Paul Mucur Date: Fri, 22 Sep 2023 21:14:27 +0100 Subject: [PATCH] Fix leak in RE2::Set#add See https://github.com/mudge/re2/issues/104 When we raise an exception in re2_set_add, the memory used by the std::string used to store the error message is never freed so we need to free it ourselves manually. However, we also need a copy of what is inside it to return to the user so we turn that into a C string first. The maximum message size of 100 is taken from the length of the prefix of the message (33 characters) and the longest error message currently in RE2 (35 characters) plus a little extra in case new releases of RE2 add longer messages. Thanks to @peterzhu2118 for both authoring ruby_memcheck and helping find the source of these leaks. --- ext/re2/re2.cc | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ext/re2/re2.cc b/ext/re2/re2.cc index 89bcba5..e4858a7 100644 --- a/ext/re2/re2.cc +++ b/ext/re2/re2.cc @@ -1589,7 +1589,13 @@ static VALUE re2_set_add(VALUE self, VALUE pattern) { int index = s->set->Add(regex, &err); if (index < 0) { - rb_raise(rb_eArgError, "str rejected by RE2::Set->Add(): %s", err.c_str()); + char msg[100]; + snprintf(msg, sizeof(msg), "str rejected by RE2::Set->Add(): %s", + err.c_str()); + + /* Manually destruct the error string before we throw an exception. */ + err.~basic_string(); + rb_raise(rb_eArgError, "str rejected by RE2::Set->Add(): %s", msg); } return INT2FIX(index);