git_exec_path: do not return the result of getenv()
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>
Jeff King committed
Jan 9, 2017 at 01:00 UTC
007ac544011213045e3905983b4350ffec8f41f7
1 file changed
+8
-9
exec_cmd.c
+8
-9
@@ -68,20 +68,19 @@ void git_set_argv_exec_path(const char *exec_path)
68
/* Returns the highest-priority, location to look for git programs. */
69
const char *git_exec_path(void)
70
{
71
- const char *env;
72
- static char *system_exec_path;
71
+ static char *cached_exec_path;
72
73
if (argv_exec_path)
74
return argv_exec_path;
75
77
- env = getenv(EXEC_PATH_ENVIRONMENT);
78
- if (env && *env) {
79
- return env;
76
+ if (!cached_exec_path) {
77
+ const char *env = getenv(EXEC_PATH_ENVIRONMENT);
78
+ if (env && *env)
79
+ cached_exec_path = xstrdup(env);
80
+ else
81
+ cached_exec_path = system_path(GIT_EXEC_PATH);
82
}
81
-
82
- if (!system_exec_path)
83
- system_exec_path = system_path(GIT_EXEC_PATH);
84
- return system_exec_path;
83
+ return cached_exec_path;
84
}
85
86
static void add_path(struct strbuf *out, const char *path)