]> git.ipfire.org Git - thirdparty/systemd.git/blobdiff - src/basic/alloc-util.c
blockdev-util: add correct API for detecting if block device has partition scanning...
[thirdparty/systemd.git] / src / basic / alloc-util.c
index f4bd33f4e014246a9c9e68f8f75e0023541a967d..5951e8c3d590c91f325364454d44aa08087889bd 100644 (file)
@@ -1,5 +1,6 @@
 /* SPDX-License-Identifier: LGPL-2.1+ */
 
+#include <malloc.h>
 #include <stdint.h>
 #include <string.h>
 
@@ -63,6 +64,29 @@ void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
         if (!q)
                 return NULL;
 
+        if (size > 0) {
+                size_t bn;
+
+                /* Adjust for the 64 byte minimum */
+                newalloc = a / size;
+
+                bn = malloc_usable_size(q) / size;
+                if (bn > newalloc) {
+                        void *qq;
+
+                        /* The actual size allocated is larger than what we asked for. Let's call realloc() again to
+                         * take possession of the extra space. This should be cheap, since libc doesn't have to move
+                         * the memory for this. */
+
+                        qq = reallocarray(q, bn, size);
+                        if (_likely_(qq)) {
+                                *p = qq;
+                                *allocated = bn;
+                                return qq;
+                        }
+                }
+        }
+
         *p = q;
         *allocated = newalloc;
         return q;