@@ -309,13 +309,19 @@ std::vector<std::string> ArgcArgvToVector(int argc, char* argv[]) {
309
309
310
310
char ** VectorToArgcArgv (const std::vector<std::string>& args_vector,
311
311
int * argc) {
312
- char ** argv = new char *[args_vector.size ()];
312
+ // Ensure that `argv` ends with a null terminator. This is a POSIX requirement
313
+ // (see https://man7.org/linux/man-pages/man2/execve.2.html) and googletest
314
+ // relies on it. Without this null terminator, the
315
+ // `ParseGoogleTestFlagsOnlyImpl()` function in googletest accesses invalid
316
+ // memory and causes an Address Sanitizer failure.
317
+ char ** argv = new char *[args_vector.size () + 1 ];
313
318
for (int i = 0 ; i < args_vector.size (); ++i) {
314
319
const char * arg = args_vector[i].c_str ();
315
320
char * arg_copy = new char [std::strlen (arg) + 1 ];
316
321
std::strcpy (arg_copy, arg);
317
322
argv[i] = arg_copy;
318
323
}
324
+ argv[args_vector.size ()] = nullptr ;
319
325
*argc = static_cast <int >(args_vector.size ());
320
326
return argv;
321
327
}
@@ -348,14 +354,11 @@ char** EditMainArgsForGoogleTest(int* argc, char* argv[]) {
348
354
// e.g. modified_args.push_back("--gtest_list_tests");
349
355
// e.g. modified_args.push_back("--gtest_filter=MyTestFixture.MyTest");
350
356
351
- // Avoid the memory leaks documented below if there were no arg changes.
352
- if (modified_args == original_args) {
353
- return argv;
354
- }
355
-
356
357
// Create a new `argv` with the elements from the `modified_args` vector and
357
358
// write the new count back to `argc`. The memory leaks produced by
358
359
// `VectorToArgcArgv` acceptable because they last for the entire application.
360
+ // Calling `VectorToArgcArgv` also fixes an invalid memory access performed by
361
+ // googletest by adding the required null element to the end of `argv`.
359
362
return VectorToArgcArgv (modified_args, argc);
360
363
}
361
364
0 commit comments