@@ -254,11 +254,6 @@ std::string PCRE2Wrapper::substitute(const std::string& orig_str,
254254 pcre2_match_data* match_data = pcre2_match_data_create_from_pattern (m_compiled, NULL );
255255 PCRE2_SIZE subject_length = orig_str.size ();
256256
257- // Usually found pattern is replaced by shorter string, but set 3 times more space for safety.
258- // Allocate dynamically since lenght depends dynamically on the lenght of input string.
259- // Allocated memory will be freed at the exit from function.
260- auto buffer = (PCRE2_UCHAR*) std::malloc (sizeof (PCRE2_UCHAR) * subject_length * 3 );
261-
262257 // Check if the string matches the pattern
263258 int match_result = pcre2_match (
264259 m_compiled,
@@ -272,7 +267,17 @@ std::string PCRE2Wrapper::substitute(const std::string& orig_str,
272267 pcre2_match_data_free (match_data);
273268 return orig_str;
274269 }
275-
270+
271+ // Usually found pattern is replaced by shorter string, but set 3 times more space for safety.
272+ // Allocate dynamically since lenght depends dynamically on the lenght of input string.
273+ // Allocated memory will be freed at the exit from function.
274+ auto buffer = (PCRE2_UCHAR*) std::malloc (sizeof (PCRE2_UCHAR) * subject_length * 3 );
275+ if (buffer == nullptr ) {
276+ std::cerr << " Memory allocation failed" << std::endl;
277+ pcre2_match_data_free (match_data);
278+ return orig_str;
279+ }
280+
276281 int rc = pcre2_substitute (
277282 m_compiled,
278283 (PCRE2_SPTR) orig_str.c_str (), orig_str.size (),
@@ -292,6 +297,7 @@ std::string PCRE2Wrapper::substitute(const std::string& orig_str,
292297 std::cerr << " PCRE2 substitution failed with error code " << rc << std::endl;
293298 }
294299 pcre2_match_data_free (match_data);
300+ std::free (buffer);
295301 return orig_str;
296302 }
297303 auto res = std::string (reinterpret_cast <char *>(buffer), subject_length);
0 commit comments