]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/alloc-util.c
tree-wide: drop license boilerplate
[thirdparty/systemd.git] / src / basic / alloc-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
b5efdb8a
LP
2/***
3 This file is part of systemd.
4
5 Copyright 2010 Lennart Poettering
b5efdb8a
LP
6***/
7
11c3a366
TA
8#include <stdint.h>
9#include <string.h>
10
b5efdb8a 11#include "alloc-util.h"
11c3a366 12#include "macro.h"
b5efdb8a
LP
13#include "util.h"
14
15void* memdup(const void *p, size_t l) {
c165d97d 16 void *ret;
b5efdb8a 17
c165d97d
LP
18 assert(l == 0 || p);
19
20 ret = malloc(l);
21 if (!ret)
22 return NULL;
23
24 memcpy(ret, p, l);
25 return ret;
26}
27
d40c54fe 28void* memdup_suffix0(const void *p, size_t l) {
c165d97d
LP
29 void *ret;
30
31 assert(l == 0 || p);
32
33 /* The same as memdup() but place a safety NUL byte after the allocated memory */
b5efdb8a 34
c165d97d
LP
35 ret = malloc(l + 1);
36 if (!ret)
b5efdb8a
LP
37 return NULL;
38
c165d97d
LP
39 *((uint8_t*) mempcpy(ret, p, l)) = 0;
40 return ret;
b5efdb8a
LP
41}
42
43void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
44 size_t a, newalloc;
45 void *q;
46
47 assert(p);
48 assert(allocated);
49
50 if (*allocated >= need)
51 return *p;
52
53 newalloc = MAX(need * 2, 64u / size);
54 a = newalloc * size;
55
56 /* check for overflows */
57 if (a < size * need)
58 return NULL;
59
60 q = realloc(*p, a);
61 if (!q)
62 return NULL;
63
64 *p = q;
65 *allocated = newalloc;
66 return q;
67}
68
69void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
70 size_t prev;
71 uint8_t *q;
72
73 assert(p);
74 assert(allocated);
75
76 prev = *allocated;
77
78 q = greedy_realloc(p, allocated, need, size);
79 if (!q)
80 return NULL;
81
82 if (*allocated > prev)
83 memzero(q + prev * size, (*allocated - prev) * size);
84
85 return q;
86}