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.
  • Loading branch information
mudge committed Sep 22, 2023
1 parent 8451fd9 commit 35870d7
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions ext/re2/re2.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1589,6 +1589,12 @@ static VALUE re2_set_add(VALUE self, VALUE pattern) {

int index = s->set->Add(regex, &err);
if (index < 0) {
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", err.c_str());
}

Expand Down

0 comments on commit 35870d7

Please sign in to comment.