]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
fileio: don't use realloc() in read_full_virtual_file()
authorLennart Poettering <lennart@poettering.net>
Wed, 17 Mar 2021 17:46:56 +0000 (18:46 +0100)
committerLennart Poettering <lennart@poettering.net>
Wed, 17 Mar 2021 17:47:56 +0000 (18:47 +0100)
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

index 8560982aab209b0f2624e7a4c2bc90018be1e303..f3a28398b784f6236900c8f9168d265f4566db65 100644 (file)
@@ -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);
         }