commit: copy saved getenv() result

We save the result of $GIT_INDEX_FILE so that we can restore it after setting it to a new value and running add--interactive. However, the pointer returned by getenv() is not guaranteed to be valid after calling setenv(). This _usually_ works fine, but can fail if libc needs to reallocate the environment block during the setenv(). Let's just duplicate the string, so we know that it remains valid. In the long run it may be more robust to teach interactive_add() to take a set of environment variables to pass along to run-command when it execs add--interactive. And then we would not have to do this save/restore dance at all. But this is an easy fix in the meantime. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Jan 11, 2019 at 17:15 UTC 406bab3811a220400da6a43da71346cbfc466fc9
1 file changed +2 -1
builtin/commit.c
+2 -1
@@ -346,7 +346,7 @@ static const char *prepare_index(int argc, const char **argv, const char *prefix
346 if (write_locked_index(&the_index, &index_lock, 0))
347 die(_("unable to create temporary index"));
348
349 - old_index_env = getenv(INDEX_ENVIRONMENT);
349 + old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
350 setenv(INDEX_ENVIRONMENT, get_lock_file_path(&index_lock), 1);
351
352 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
@@ -356,6 +356,7 @@ static const char *prepare_index(int argc, const char **argv, const char *prefix
356 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
357 else
358 unsetenv(INDEX_ENVIRONMENT);
359 + FREE_AND_NULL(old_index_env);
360
361 discard_cache();
362 read_cache_from(get_lock_file_path(&index_lock));