timespec_get: New module.
[gnulib.git] / lib / safe-alloc.c
blob45e770015671c589046d468fdedb393b70f08176
1 /* safe-alloc.c: safer memory allocation
3 Copyright (C) 2009-2021 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
8 later version.
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 */
20 #include <config.h>
22 /* Specification. */
23 #include "safe-alloc.h"
25 #include "xalloc-oversized.h"
27 #include <stdlib.h>
28 #include <stddef.h>
29 #include <errno.h>
32 /**
33 * safe_alloc_alloc_n:
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
45 int
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;
51 return 0;
54 if (xalloc_oversized (count, size))
56 errno = ENOMEM;
57 return -1;
60 if (zeroed)
61 *(void **) ptrptr = calloc (count, size);
62 else
63 *(void **) ptrptr = malloc (count * size);
65 if (*(void **) ptrptr == NULL)
66 return -1;
67 return 0;
70 /**
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
84 int
85 safe_alloc_realloc_n (void *ptrptr, size_t size, size_t count)
87 void *tmp;
88 if (size == 0 || count == 0)
90 free (*(void **) ptrptr);
91 *(void **) ptrptr = NULL;
92 return 0;
94 if (xalloc_oversized (count, size))
96 errno = ENOMEM;
97 return -1;
99 tmp = realloc (*(void **) ptrptr, size * count);
100 if (!tmp)
101 return -1;
102 *(void **) ptrptr = tmp;
103 return 0;