@@ -309,13 +309,19 @@ std::vector<std::string> ArgcArgvToVector(int argc, char* argv[]) {
309309
310310char ** VectorToArgcArgv (const std::vector<std::string>& args_vector,
311311 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 ];
313318 for (int i = 0 ; i < args_vector.size (); ++i) {
314319 const char * arg = args_vector[i].c_str ();
315320 char * arg_copy = new char [std::strlen (arg) + 1 ];
316321 std::strcpy (arg_copy, arg);
317322 argv[i] = arg_copy;
318323 }
324+ argv[args_vector.size ()] = nullptr ;
319325 *argc = static_cast <int >(args_vector.size ());
320326 return argv;
321327}
@@ -348,14 +354,11 @@ char** EditMainArgsForGoogleTest(int* argc, char* argv[]) {
348354 // e.g. modified_args.push_back("--gtest_list_tests");
349355 // e.g. modified_args.push_back("--gtest_filter=MyTestFixture.MyTest");
350356
351- // Avoid the memory leaks documented below if there were no arg changes.
352- if (modified_args == original_args) {
353- return argv;
354- }
355-
356357 // Create a new `argv` with the elements from the `modified_args` vector and
357358 // write the new count back to `argc`. The memory leaks produced by
358359 // `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`.
359362 return VectorToArgcArgv (modified_args, argc);
360363}
361364
0 commit comments