ubase

suckless linux base utils
git clone git://git.2f30.org/ubase.git
Log | Files | Refs | README | LICENSE

commit 3803adfd7eb6b85852e89ae186a1e68834ee72ca
parent 8b32decb6feabf771a06aed6f9c19fa27da7f1f6
Author: sin <sin@2f30.org>
Date:   Thu Apr 17 16:13:34 +0100

Don't hardcode the buffer size in sysctl

Diffstat:
sysctl.c | 37++++++++++++++++++++++++-------------
1 file changed, 24 insertions(+), 13 deletions(-)
diff --git a/sysctl.c b/sysctl.c @@ -12,9 +12,10 @@ getsysctl(char *variable, char **value) { char path[PATH_MAX]; char *p; - char *buf; + char *buf, c; int fd; ssize_t n; + size_t sz, i; for (p = variable; *p; p++) if (*p == '.') @@ -28,19 +29,29 @@ getsysctl(char *variable, char **value) if (fd < 0) return -1; - buf = malloc(1024); - if (!buf) { - close(fd); - return -1; - } - - n = read(fd, buf, 1023); - if (n <= 0) { - close(fd); - free(buf); - return -1; + i = 0; + sz = 1; + buf = NULL; + while (1) { + n = read(fd, &c, 1); + if (n < 0) { + close(fd); + free(buf); + return -1; + } + if (n == 0) + break; + if (i == sz - 1) { + sz *= 2; + buf = realloc(buf, sz); + if (!buf) { + close(fd); + return -1; + } + } + buf[i++] = c; } - buf[n] = '\0'; + buf[i] = '\0'; p = strrchr(buf, '\n'); if (p)