chiark / gitweb /
eceff4f246cc8d30fe1e807b436e50bb1318ba5f
[elogind.git] / src / basic / alloc-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2010 Lennart Poettering
6 ***/
7
8 #include <stdint.h>
9 #include <string.h>
10
11 #include "alloc-util.h"
12 #include "macro.h"
13 #include "util.h"
14
15 void* memdup(const void *p, size_t l) {
16         void *ret;
17
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
28 void* memdup_suffix0(const void *p, size_t l) {
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 */
34
35         ret = malloc(l + 1);
36         if (!ret)
37                 return NULL;
38
39         *((uint8_t*) mempcpy(ret, p, l)) = 0;
40         return ret;
41 }
42
43 void* 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
69 void* 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 }