From: Lennart Poettering Date: Tue, 30 Apr 2019 08:13:57 +0000 (+0200) Subject: alloc-util: reintroduce malloc_usable_size() into greedy_realloc() X-Git-Tag: v243~598^2~1 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=e59054270c6e37fd08fdd5d0231edd17c7f7495a;p=platform%2Fupstream%2Fsystemd.git alloc-util: reintroduce malloc_usable_size() into greedy_realloc() This is another attempt at d4b604baeadbb2498e4f2c3e260260eed210f5d6 and #12438 Instead of blindly using the extra allocated space, let's do so only after telling libc about it, via a second realloc(). The second realloc() should be quick, since it never has to copy memory around. --- diff --git a/src/basic/alloc-util.c b/src/basic/alloc-util.c index f4bd33f..a16db68 100644 --- a/src/basic/alloc-util.c +++ b/src/basic/alloc-util.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: LGPL-2.1+ */ +#include #include #include @@ -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 = realloc(q, bn * size); + if (_likely_(qq)) { + *p = qq; + *allocated = bn; + return qq; + } + } + } + *p = q; *allocated = newalloc; return q;