@@ -254,11 +254,6 @@ std::string PCRE2Wrapper::substitute(const std::string& orig_str,
254
254
pcre2_match_data* match_data = pcre2_match_data_create_from_pattern (m_compiled, NULL );
255
255
PCRE2_SIZE subject_length = orig_str.size ();
256
256
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
-
262
257
// Check if the string matches the pattern
263
258
int match_result = pcre2_match (
264
259
m_compiled,
@@ -272,7 +267,17 @@ std::string PCRE2Wrapper::substitute(const std::string& orig_str,
272
267
pcre2_match_data_free (match_data);
273
268
return orig_str;
274
269
}
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
+
276
281
int rc = pcre2_substitute (
277
282
m_compiled,
278
283
(PCRE2_SPTR) orig_str.c_str (), orig_str.size (),
@@ -292,6 +297,7 @@ std::string PCRE2Wrapper::substitute(const std::string& orig_str,
292
297
std::cerr << " PCRE2 substitution failed with error code " << rc << std::endl;
293
298
}
294
299
pcre2_match_data_free (match_data);
300
+ std::free (buffer);
295
301
return orig_str;
296
302
}
297
303
auto res = std::string (reinterpret_cast <char *>(buffer), subject_length);
0 commit comments