1 /* safe-alloc.c: safer memory allocation
3 Copyright (C) 2009-2020 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify it
6 under the terms of the GNU General Public License as published by the
7 Free Software Foundation; either version 3 of the License, or any
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.
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/>. */
18 /* Written by Daniel Berrange <berrange@redhat.com>, 2008 */
23 #include "safe-alloc.h"
25 #include "xalloc-oversized.h"
34 * @ptrptr: pointer to pointer for address of allocated memory
35 * @size: number of bytes to allocate
36 * @count: number of elements to allocate
38 * Allocate an array of memory 'count' elements long,
39 * each with 'size' bytes. Return the address of the
40 * allocated memory in 'ptrptr'. The newly allocated
41 * memory is filled with zeros.
43 * Return -1 on failure to allocate, zero on success
46 safe_alloc_alloc_n (void *ptrptr
, size_t size
, size_t count
, int zeroed
)
48 if (size
== 0 || count
== 0)
50 *(void **) ptrptr
= NULL
;
54 if (xalloc_oversized (count
, size
))
61 *(void **) ptrptr
= calloc (count
, size
);
63 *(void **) ptrptr
= malloc (count
* size
);
65 if (*(void **) ptrptr
== NULL
)
71 * safe_alloc_realloc_n:
72 * @ptrptr: pointer to pointer for address of allocated memory
73 * @size: number of bytes to allocate
74 * @count: number of elements in array
76 * Resize the block of memory in 'ptrptr' to be an array of
77 * 'count' elements, each 'size' bytes in length. Update 'ptrptr'
78 * with the address of the newly allocated memory. On failure,
79 * 'ptrptr' is not changed and still points to the original memory
80 * block. The newly allocated memory is filled with zeros.
82 * Return -1 on failure to allocate, zero on success
85 safe_alloc_realloc_n (void *ptrptr
, size_t size
, size_t count
)
88 if (size
== 0 || count
== 0)
90 free (*(void **) ptrptr
);
91 *(void **) ptrptr
= NULL
;
94 if (xalloc_oversized (count
, size
))
99 tmp
= realloc (*(void **) ptrptr
, size
* count
);
102 *(void **) ptrptr
= tmp
;