git_exec_path: do not return the result of getenv()
authorJeff King <peff@peff.net>
Mon, 9 Jan 2017 06:00:12 +0000 (01:00 -0500)
committerJunio C Hamano <gitster@pobox.com>
Mon, 9 Jan 2017 09:29:50 +0000 (01:29 -0800)
The result of getenv() is not guaranteed by POSIX to last
beyond another call to getenv(), or setenv(), etc. We
should duplicate the string before returning to the caller
to avoid any surprises.

We already keep a cached pointer to avoid repeatedly leaking
the result of system_path(). We can use the same pointer
here to avoid allocating and leaking for each call.

Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
exec_cmd.c
index eae56fefba9953b9b589a2b17a7a282d7120754c..31ceb3338334a412128f5f4750f832b110545cdf 100644 (file)
@@ -68,20 +68,19 @@ void git_set_argv_exec_path(const char *exec_path)
 /* Returns the highest-priority, location to look for git programs. */
 const char *git_exec_path(void)
 {
-       const char *env;
-       static char *system_exec_path;
+       static char *cached_exec_path;
 
        if (argv_exec_path)
                return argv_exec_path;
 
-       env = getenv(EXEC_PATH_ENVIRONMENT);
-       if (env && *env) {
-               return env;
+       if (!cached_exec_path) {
+               const char *env = getenv(EXEC_PATH_ENVIRONMENT);
+               if (env && *env)
+                       cached_exec_path = xstrdup(env);
+               else
+                       cached_exec_path = system_path(GIT_EXEC_PATH);
        }
-
-       if (!system_exec_path)
-               system_exec_path = system_path(GIT_EXEC_PATH);
-       return system_exec_path;
+       return cached_exec_path;
 }
 
 static void add_path(struct strbuf *out, const char *path)