Skip to content

Commit

Permalink
Fix leak in RE2::Set#add
Browse files Browse the repository at this point in the history
See #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.
  • Loading branch information
mudge committed Sep 22, 2023
1 parent 60e3d3f commit 064d49a
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion ext/re2/re2.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 064d49a

Please sign in to comment.