Debian Codegraph @

lib/xmalloc.c

raw
1 /* xmalloc.c -- malloc with out of memory checking
2
3 Copyright (C) 1990-2000, 2002-2006, 2008-2026 Free Software Foundation, Inc.
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17
18 #define XALLOC_INLINE _GL_EXTERN_INLINE
19 #include <config.h>
20 #include "xalloc.h"
21
22 #include "ialloc.h"
23 #include "minmax.h"
24
25 #include <stdckdint.h>
26 #include <stdlib.h>
27 #include <stdint.h>
28 #include <string.h>
29
30 /* Pacify GCC up to at least 15.2, which otherwise would incorrectly
31 complain about check_nonnull. */
32 #if _GL_GNUC_PREREQ (4, 6)
33 # pragma GCC diagnostic ignored "-Wsuggest-attribute=pure"
34 #endif
35
36 static void *
37 check_nonnull (void *p)
38 {
39 if (!p)
40 xalloc_die ();
41 return p;
42 }
43
44 /* Allocate S bytes of memory dynamically, with error checking. */
45
46 void *
47 xmalloc (size_t s)
48 {
49 return check_nonnull (malloc (s));
50 }
51
52 void *
53 ximalloc (idx_t s)
54 {
55 return check_nonnull (imalloc (s));
56 }
57
58 char *
59 xcharalloc (size_t n)
60 {
61 return XNMALLOC (n, char);
62 }
63
64 /* Change the size of an allocated block of memory P to S bytes,
65 with error checking. */
66
67 void *
68 xrealloc (void *p, size_t s)
69 {
70 void *r = realloc (p, s);
71 if (!r)
72 xalloc_die ();
73 return r;
74 }
75
76 void *
77 xirealloc (void *p, idx_t s)
78 {
79 return check_nonnull (irealloc (p, s));
80 }
81
82 /* Change the size of an allocated block of memory P to an array of N
83 objects each of S bytes, with error checking. */
84
85 void *
86 xreallocarray (void *p, size_t n, size_t s)
87 {
88 void *r = reallocarray (p, n, s);
89 if (!r)
90 xalloc_die ();
91 return r;
92 }
93
94 void *
95 xireallocarray (void *p, idx_t n, idx_t s)
96 {
97 return check_nonnull (ireallocarray (p, n, s));
98 }
99
100 /* Allocate an array of N objects, each with S bytes of memory,
101 dynamically, with error checking. S must be nonzero. */
102
103 void *
104 xnmalloc (size_t n, size_t s)
105 {
106 return xreallocarray (NULL, n, s);
107 }
108
109 void *
110 xinmalloc (idx_t n, idx_t s)
111 {
112 return xireallocarray (NULL, n, s);
113 }
114
115 /* If P is null, allocate a block of at least *PS bytes; otherwise,
116 reallocate P so that it contains more than *PS bytes. *PS must be
117 nonzero unless P is null. Set *PS to the new block's size, and
118 return the pointer to the new block. *PS is never set to zero, and
119 the returned pointer is never null. */
120
121 void *
122 x2realloc (void *p, size_t *ps)
123 {
124 return x2nrealloc (p, ps, 1);
125 }
126
127 /* If P is null, allocate a block of at least *PN such objects;
128 otherwise, reallocate P so that it contains more than *PN objects
129 each of S bytes. S must be nonzero. Set *PN to the new number of
130 objects, and return the pointer to the new block. *PN is never set
131 to zero, and the returned pointer is never null.
132
133 Repeated reallocations are guaranteed to make progress, either by
134 allocating an initial block with a nonzero size, or by allocating a
135 larger block.
136
137 In the following implementation, nonzero sizes are increased by a
138 factor of approximately 1.5 so that repeated reallocations have
139 O(N) overall cost rather than O(N**2) cost, but the
140 specification for this function does not guarantee that rate.
141
142 Here is an example of use:
143
144 int *p = NULL;
145 size_t used = 0;
146 size_t allocated = 0;
147
148 void
149 append_int (int value)
150 {
151 if (used == allocated)
152 p = x2nrealloc (p, &allocated, sizeof *p);
153 p[used++] = value;
154 }
155
156 This causes x2nrealloc to allocate a block of some nonzero size the
157 first time it is called.
158
159 To have finer-grained control over the initial size, set *PN to a
160 nonzero value before calling this function with P == NULL. For
161 example:
162
163 int *p = NULL;
164 size_t used = 0;
165 size_t allocated = 0;
166 size_t allocated1 = 1000;
167
168 void
169 append_int (int value)
170 {
171 if (used == allocated)
172 {
173 p = x2nrealloc (p, &allocated1, sizeof *p);
174 allocated = allocated1;
175 }
176 p[used++] = value;
177 }
178
179 */
180
181 void *
182 x2nrealloc (void *p, size_t *pn, size_t s)
183 {
184 size_t n = *pn;
185
186 if (! p)
187 {
188 if (! n)
189 {
190 /* The approximate size to use for initial small allocation
191 requests, when the invoking code specifies an old size of
192 zero. This is the largest "small" request for the GNU C
193 library malloc. */
194 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
195
196 n = DEFAULT_MXFAST / s;
197 n += !n;
198 }
199 }
200 else
201 {
202 /* Set N = floor (1.5 * N) + 1 to make progress even if N == 0. */
203 if (ckd_add (&n, n, (n >> 1) + 1))
204 xalloc_die ();
205 }
206
207 p = xreallocarray (p, n, s);
208 *pn = n;
209 return p;
210 }
211
212 /* Grow PA, which points to an array of *PN items, and return the
213 location of the reallocated array, updating *PN to reflect its
214 new size. The new array will contain at least N_INCR_MIN more
215 items, but will not contain more than N_MAX items total.
216 S is the size of each item, in bytes.
217
218 S and N_INCR_MIN must be positive. *PN must be
219 nonnegative. If N_MAX is -1, it is treated as if it were
220 infinity.
221
222 If PA is null, then allocate a new array instead of reallocating
223 the old one.
224
225 Thus, to grow an array A without saving its old contents, do
226 { free (A); A = xpalloc (NULL, &AITEMS, ...); }. */
227
228 void *
229 xpalloc (void *pa, idx_t *pn, idx_t n_incr_min, ptrdiff_t n_max, idx_t s)
230 {
231 /* The approximate size to use for initial small allocation
232 requests. This is the largest "small" request for the GNU C
233 library malloc. */
234 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
235
236 idx_t n0 = *pn;
237
238 /* If the array is tiny, grow it to about (but no greater than)
239 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
240 Adjust the growth according to three constraints: N_INCR_MIN,
241 N_MAX, and what the C language can represent safely. */
242
243 idx_t n;
244 if (ckd_add (&n, n0, n0 >> 1))
245 n = IDX_MAX;
246 if (0 <= n_max && n_max < n)
247 n = n_max;
248
249 /* NBYTES is of a type suitable for holding the count of bytes in an object.
250 This is typically idx_t, but it should be size_t on (theoretical?)
251 platforms where SIZE_MAX < IDX_MAX so xpalloc does not pass
252 values greater than SIZE_MAX to xrealloc. */
253 #if IDX_MAX <= SIZE_MAX
254 idx_t nbytes;
255 #else
256 size_t nbytes;
257 #endif
258 idx_t adjusted_nbytes
259 = (ckd_mul (&nbytes, n, s)
260 ? MIN (IDX_MAX, SIZE_MAX)
261 : nbytes < DEFAULT_MXFAST ? DEFAULT_MXFAST : 0);
262 if (adjusted_nbytes)
263 {
264 n = adjusted_nbytes / s;
265 nbytes = adjusted_nbytes - adjusted_nbytes % s;
266 }
267
268 if (! pa)
269 *pn = 0;
270 if (n - n0 < n_incr_min
271 && (ckd_add (&n, n0, n_incr_min)
272 || (0 <= n_max && n_max < n)
273 || ckd_mul (&nbytes, n, s)))
274 xalloc_die ();
275 pa = xrealloc (pa, nbytes);
276 *pn = n;
277 return pa;
278 }
279
280 /* Allocate S bytes of zeroed memory dynamically, with error checking.
281 There's no need for xnzalloc (N, S), since it would be equivalent
282 to xcalloc (N, S). */
283
284 void *
285 xzalloc (size_t s)
286 {
287 return xcalloc (s, 1);
288 }
289
290 void *
291 xizalloc (idx_t s)
292 {
293 return xicalloc (s, 1);
294 }
295
296 /* Allocate zeroed memory for N elements of S bytes, with error
297 checking. S must be nonzero. */
298
299 void *
300 xcalloc (size_t n, size_t s)
301 {
302 return check_nonnull (calloc (n, s));
303 }
304
305 void *
306 xicalloc (idx_t n, idx_t s)
307 {
308 return check_nonnull (icalloc (n, s));
309 }
310
311 /* Clone an object P of size S, with error checking. There's no need
312 for xnmemdup (P, N, S), since xmemdup (P, N * S) works without any
313 need for an arithmetic overflow check. */
314
315 void *
316 xmemdup (void const *p, size_t s)
317 {
318 return memcpy (xmalloc (s), p, s);
319 }
320
321 void *
322 ximemdup (void const *p, idx_t s)
323 {
324 return memcpy (ximalloc (s), p, s);
325 }
326
327 /* Clone an object P of size S, with error checking. Append
328 a terminating NUL byte. */
329
330 char *
331 ximemdup0 (void const *p, idx_t s)
332 {
333 char *result = ximalloc (s + 1);
334 result[s] = 0;
335 return memcpy (result, p, s);
336 }
337
338 /* Clone STRING. */
339
340 char *
341 xstrdup (char const *string)
342 {
343 return xmemdup (string, strlen (string) + 1);
344 }