From b235b03138aec745c3903619b793c1d7edc01e9d Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Wed, 17 Mar 2021 18:46:56 +0100 Subject: [PATCH] fileio: don't use realloc() in read_full_virtual_file() We aren't interested in the data previousl read, hence free() followed by malloc() is typically better since it means libc doesn't have to restore the contained data needlessly. --- src/basic/fileio.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/basic/fileio.c b/src/basic/fileio.c index 8560982aab..f3a28398b7 100644 --- a/src/basic/fileio.c +++ b/src/basic/fileio.c @@ -368,7 +368,6 @@ int read_full_virtual_file(const char *filename, char **ret_contents, size_t *re struct stat st; size_t n, size; int n_retries; - char *p; assert(ret_contents); @@ -413,10 +412,9 @@ int read_full_virtual_file(const char *filename, char **ret_contents, size_t *re if (size > READ_FULL_BYTES_MAX) return -E2BIG; - p = realloc(buf, size + 1); - if (!p) + buf = malloc(size + 1); + if (!buf) return -ENOMEM; - buf = TAKE_PTR(p); for (;;) { ssize_t k; @@ -445,12 +443,18 @@ int read_full_virtual_file(const char *filename, char **ret_contents, size_t *re if (lseek(fd, 0, SEEK_SET) < 0) return -errno; + + buf = mfree(buf); } if (n < size) { + char *p; + + /* Return rest of the buffer to libc */ p = realloc(buf, n + 1); if (!p) return -ENOMEM; + buf = TAKE_PTR(p); }