From 35870d7da8bc882f6e44c9aa51095c186ad8500f 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. --- ext/re2/re2.cc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ext/re2/re2.cc b/ext/re2/re2.cc index 89bcba5..4b23de4 100644 --- a/ext/re2/re2.cc +++ b/ext/re2/re2.cc @@ -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()); }