From 30986cb22e2f26d83cbb8516bf25d3fa5c9a577d Mon Sep 17 00:00:00 2001 From: Tobias Stoeckmann Date: Sat, 11 Jul 2015 21:28:47 +0200 Subject: [PATCH 1/2] Handle out of memory conditions. malloc and realloc could return NULL when no memory is available. The code doesn't handle errors, so use xmalloc/xrealloc instead. While at it, sync alloclen's type with len's type, so both are ssize_t. --- pwdx.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pwdx.c b/pwdx.c index 07bedfc8..3e0afca6 100644 --- a/pwdx.c +++ b/pwdx.c @@ -65,7 +65,7 @@ int main(int argc, char *argv[]) { int ch; int retval = 0, i; - int alloclen = 128; + ssize_t alloclen = 128; char *pathbuf; static const struct option longopts[] = { @@ -99,7 +99,7 @@ int main(int argc, char *argv[]) if (argc == 0) usage(stderr); - pathbuf = malloc(alloclen); + pathbuf = xmalloc(alloclen); for (i = 0; i < argc; i++) { char *s; @@ -128,7 +128,7 @@ int main(int argc, char *argv[]) */ while ((len = readlink(buf, pathbuf, alloclen)) == alloclen) { alloclen *= 2; - pathbuf = realloc(pathbuf, alloclen); + pathbuf = xrealloc(pathbuf, alloclen); } free(buf); From e8430bad0057c8880f2f453ea90b8414ed30d0d5 Mon Sep 17 00:00:00 2001 From: Tobias Stoeckmann Date: Sat, 11 Jul 2015 21:30:31 +0200 Subject: [PATCH 2/2] Fix readlink's do-while-loop The function pid_link tries to handle programs which contain very long paths to their executables. If 1024 bytes are not enough to contain the path, the loop wants to get more and more space until the path can fit. The loop's condition does not fit though. readlink will never return a value higher than its supplied size limit, which is "path_alloc_size - 1", therefore the loop-check of "len == path_alloc_size" will always be false: the loop will never be repeated. While at it, the if-condition inside the loop's body can be omitted, because it is always true. --- pidof.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/pidof.c b/pidof.c index d1a9f315..8712d113 100644 --- a/pidof.c +++ b/pidof.c @@ -103,20 +103,18 @@ static char *pid_link (pid_t pid, const char *base_name) { char link [PROCPATHLEN]; char *result; - int path_alloc_size; - int len; + ssize_t path_alloc_size; + ssize_t len; snprintf(link, sizeof(link), "/proc/%d/%s", pid, base_name); len = path_alloc_size = 0; result = NULL; do { - if (len == path_alloc_size) { - grow_size (path_alloc_size); - result = (char *) xrealloc (result, path_alloc_size); - } + grow_size(path_alloc_size); + result = xrealloc(result, path_alloc_size); - if ((len = readlink(link, result, path_alloc_size - 1)) < 0) { + if ((len = readlink(link, result, path_alloc_size)) < 0) { len = 0; break; }