]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/alloc-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
7 #include "alloc-util.h"
9 #include "memory-util.h"
11 void* memdup(const void *p
, size_t l
) {
24 void* memdup_suffix0(const void *p
, size_t l
) {
29 /* The same as memdup() but place a safety NUL byte after the allocated memory */
31 if (_unlikely_(l
== SIZE_MAX
)) /* prevent overflow */
38 *((uint8_t*) mempcpy(ret
, p
, l
)) = 0;
42 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
49 if (*allocated
>= need
)
52 if (_unlikely_(need
> SIZE_MAX
/2)) /* Overflow check */
56 if (size_multiply_overflow(newalloc
, size
))
60 if (a
< 64) /* Allocate at least 64 bytes */
70 /* Adjust for the 64 byte minimum */
73 bn
= malloc_usable_size(q
) / size
;
77 /* The actual size allocated is larger than what we asked for. Let's call realloc() again to
78 * take possession of the extra space. This should be cheap, since libc doesn't have to move
79 * the memory for this. */
81 qq
= reallocarray(q
, bn
, size
);
91 *allocated
= newalloc
;
95 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
104 q
= greedy_realloc(p
, allocated
, need
, size
);
108 if (*allocated
> prev
)
109 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);