From 3c2fc82b6ee9c451a87e2d3ade2983f9dd1e3999 Mon Sep 17 00:00:00 2001 From: Christophe CURIS Date: Sun, 9 Jun 2013 16:28:48 +0200 Subject: [PATCH] WUtil: Avoid memory leak and misbehaviour on internal function 'getuserhomedir' If the function was called more than once with different usernames it would always return the path for the user on the first call, which is not what would be expected. Furthermore, if the function succeeds it allocated memory to save this path but it was never freed. The good thing is that the use case for this function is so rare that it is improbable it was ever called, which explains why it was never seen. The new code always behaves as expected, and does not allocate memory anymore to avoid wasting time and memory for such small things, which is acceptable because this function is local. Signed-off-by: Christophe CURIS --- WINGs/findfile.c | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/WINGs/findfile.c b/WINGs/findfile.c index f18aa3ae..42845d03 100644 --- a/WINGs/findfile.c +++ b/WINGs/findfile.c @@ -67,25 +67,31 @@ char *wgethomedir() return home; } -static char *getuserhomedir(const char *username) +/* + * Return the home directory for the specified used + * + * If user not found, returns NULL, otherwise always returns a path that is + * statically stored. + * + * Please note you must use the path before any other call to 'getpw*' or it + * may be erased. This is a design choice to avoid duplication considering + * the use case for this function. + */ +static const char *getuserhomedir(const char *username) { - static char *home = NULL; + static const char default_home[] = "/"; struct passwd *user; - if (home) - return home; - user = getpwnam(username); if (!user) { werror(_("could not get password entry for user %s"), username); return NULL; } if (!user->pw_dir) - home = "/"; + return default_home; else - home = wstrdup(user->pw_dir); + return user->pw_dir; - return home; } char *wexpandpath(const char *path) @@ -98,7 +104,7 @@ char *wexpandpath(const char *path) memset(buffer, 0, PATH_MAX + 2); if (*path == '~') { - char *home; + const char *home; path++; if (*path == '/' || *path == 0) {