Fix memory leak in which() on realloc() failure

Avoid leaking memory when realloc() fails by using a temporary pointer
and only updating the original on success. Also remove redundant NULL
check before free().

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
Joachim Wiberg committed 2025-11-22 20:48:35 +01:00
1 parent f0cb0b7bf2
commit 958502d982
1 file changed
+9 -6
+9 -6
View File
@@ -53,8 +53,9 @@ static char *strip_args(char *path)
*/ */
char *which(const char *cmd) char *which(const char *cmd)
{ {
char *ptr, *env, *path = NULL;
size_t pathlen = 0; size_t pathlen = 0;
char *ptr, *tok, *env, *path = NULL; const char *tok;
if (!cmd) { if (!cmd) {
errno = EINVAL; errno = EINVAL;
@@ -69,9 +70,7 @@ char *which(const char *cmd)
if (!access(path, X_OK)) if (!access(path, X_OK))
return path; return path;
if (path) free(path);
free(path);
return NULL; return NULL;
} }
@@ -88,11 +87,15 @@ char *which(const char *cmd)
size_t len = strlen(tok) + strlen(cmd) + 2; size_t len = strlen(tok) + strlen(cmd) + 2;
if (pathlen < len) { if (pathlen < len) {
path = realloc(path, len); char *tmp = realloc(path, len);
if (!path) {
if (!tmp) {
free(path);
free(env); free(env);
return NULL; return NULL;
} }
path = tmp;
pathlen = len; pathlen = len;
} }