1
0
mirror of https://github.com/systemd/systemd.git synced 2024-10-30 14:55:37 +03:00

alloc-util: reintroduce malloc_usable_size() into greedy_realloc()

This is another attempt at d4b604baea 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.
This commit is contained in:
Lennart Poettering 2019-04-30 10:13:57 +02:00
parent 64538af89b
commit e59054270c

View File

@ -1,5 +1,6 @@
/* SPDX-License-Identifier: LGPL-2.1+ */ /* SPDX-License-Identifier: LGPL-2.1+ */
#include <malloc.h>
#include <stdint.h> #include <stdint.h>
#include <string.h> #include <string.h>
@ -63,6 +64,29 @@ void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
if (!q) if (!q)
return NULL; 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; *p = q;
*allocated = newalloc; *allocated = newalloc;
return q; return q;