Re: [hackers] [dmenu] readstdin: reduce memory-usage by duplicating the line from getline() || Hiltjo Posthuma

From: NRK <nrk_AT_disroot.org>
Date: Thu, 9 Mar 2023 03:26:46 +0600

Was wondering what happens if we instead use realloc to shrink the
buffer. On my (glibc v2.36) system, it doesn't seem to make any
difference, though.

        index 27b7a30..fc127ae 100644
        _AT_@ -562,6 +562,8 @@ readstdin(void)
                         }
                         if (line[len - 1] == '\n')
                                 line[len - 1] = '\0';
        + if (!(line = realloc(line, len + 1)))
        + die("realloc:");
                         items[i].text = line;
                         items[i].out = 0;
                         line = NULL; /* next call of getline() allocates a new line */

Tested with `seq 0 128000 | ./dmenu`:

        Old (getline) ~29K
        realloc ~29K
        new (strdup) ~17K

Maybe using `malloc(len + 1) + memcpy` would be better for larger
strings instead of strdup. But hopefully no one is going to be piping
gigabytes long lines into dmenu for it to matter :) So it's fine as is.

- NRK
Received on Wed Mar 08 2023 - 22:26:46 CET

This archive was generated by hypermail 2.3.0 : Wed Mar 08 2023 - 22:36:36 CET