readstdin: reduce memory-usage by duplicating the line from getline()

Improves upon commit 32db2b1251

The getline() implementation often uses a more greedy way of allocating memory.
Using this buffer directly and forcing an allocation (by setting it to NULL)
would waste a bit of extra space, depending on the implementation of course.

Tested on musl libc and glibc.
The current glibc version allocates a minimum of 120 bytes per line.
For smaller lines musl libc seems less wasteful but still wastes a few bytes
per line.

On a dmenu_path listing on my system the memory usage was about 350kb (old) vs
30kb (new) on Void Linux glibc.

Side-note that getline() also reads NUL bytes in lines, while strdup() would
read until the NUL byte. Since dmenu reads text lines either is probably
fine(tm). Also rename junk to linesiz.
This commit is contained in:
Hiltjo Posthuma 2023-03-08 21:20:52 +01:00
parent ba1a347dca
commit dfbbf7f6e1
1 changed files with 5 additions and 4 deletions

View File

@ -550,11 +550,11 @@ static void
readstdin(void) readstdin(void)
{ {
char *line = NULL; char *line = NULL;
size_t i, junk, itemsiz = 0; size_t i, itemsiz = 0, linesiz = 0;
ssize_t len; ssize_t len;
/* read each line from stdin and add it to the item list */ /* read each line from stdin and add it to the item list */
for (i = 0; (len = getline(&line, &junk, stdin)) != -1; i++) { for (i = 0; (len = getline(&line, &linesiz, stdin)) != -1; i++) {
if (i + 1 >= itemsiz) { if (i + 1 >= itemsiz) {
itemsiz += 256; itemsiz += 256;
if (!(items = realloc(items, itemsiz * sizeof(*items)))) if (!(items = realloc(items, itemsiz * sizeof(*items))))
@ -562,9 +562,10 @@ readstdin(void)
} }
if (line[len - 1] == '\n') if (line[len - 1] == '\n')
line[len - 1] = '\0'; line[len - 1] = '\0';
items[i].text = line; if (!(items[i].text = strdup(line)))
die("strdup:");
items[i].out = 0; items[i].out = 0;
line = NULL; /* next call of getline() allocates a new line */
} }
free(line); free(line);
if (items) if (items)