]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/alloc-util.c
util-lib: split out allocation calls into alloc-util.[ch]
[thirdparty/systemd.git] / src / basic / alloc-util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include "alloc-util.h"
23 #include "util.h"
24
25 void* memdup(const void *p, size_t l) {
26 void *r;
27
28 assert(p);
29
30 r = malloc(l);
31 if (!r)
32 return NULL;
33
34 memcpy(r, p, l);
35 return r;
36 }
37
38 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
39 size_t a, newalloc;
40 void *q;
41
42 assert(p);
43 assert(allocated);
44
45 if (*allocated >= need)
46 return *p;
47
48 newalloc = MAX(need * 2, 64u / size);
49 a = newalloc * size;
50
51 /* check for overflows */
52 if (a < size * need)
53 return NULL;
54
55 q = realloc(*p, a);
56 if (!q)
57 return NULL;
58
59 *p = q;
60 *allocated = newalloc;
61 return q;
62 }
63
64 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
65 size_t prev;
66 uint8_t *q;
67
68 assert(p);
69 assert(allocated);
70
71 prev = *allocated;
72
73 q = greedy_realloc(p, allocated, need, size);
74 if (!q)
75 return NULL;
76
77 if (*allocated > prev)
78 memzero(q + prev * size, (*allocated - prev) * size);
79
80 return q;
81 }