Prefer #include <...> for system headers.
[libiconv.git] / gnulib-local / lib / xmalloc.c
blob0fd80ac0a0119632fa1e088ec99f126c781a9b84
1 /* xmalloc.c -- malloc with out of memory checking
2 Copyright (C) 1990-2024 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 #include <config.h>
19 /* Specification. */
20 #include "xalloc.h"
22 #include <stdlib.h>
24 #include <error.h>
25 #include "gettext.h"
27 #define _(str) gettext (str)
30 /* Exit value when the requested amount of memory is not available.
31 The caller may set it to some other value. */
32 int xmalloc_exit_failure = EXIT_FAILURE;
34 void
35 xalloc_die ()
37 error (xmalloc_exit_failure, 0, _("memory exhausted"));
38 /* _Noreturn cannot be given to error, since it may return if
39 its first argument is 0. To help compilers understand the
40 xalloc_die does terminate, call exit. */
41 exit (EXIT_FAILURE);
44 static void *
45 fixup_null_alloc (size_t n)
47 void *p;
49 p = NULL;
50 if (n == 0)
51 p = malloc ((size_t) 1);
52 if (p == NULL)
53 xalloc_die ();
54 return p;
57 /* Allocate N bytes of memory dynamically, with error checking. */
59 void *
60 xmalloc (size_t n)
62 void *p;
64 p = malloc (n);
65 if (p == NULL)
66 p = fixup_null_alloc (n);
67 return p;
70 /* Allocate memory for NMEMB elements of SIZE bytes, with error checking.
71 SIZE must be > 0. */
73 void *
74 xnmalloc (size_t nmemb, size_t size)
76 size_t n;
77 void *p;
79 if (xalloc_oversized (nmemb, size))
80 xalloc_die ();
81 n = nmemb * size;
82 p = malloc (n);
83 if (p == NULL)
84 p = fixup_null_alloc (n);
85 return p;
88 /* Allocate SIZE bytes of memory dynamically, with error checking,
89 and zero it. */
91 void *
92 xzalloc (size_t size)
94 void *p;
96 p = xmalloc (size);
97 memset (p, 0, size);
98 return p;
101 /* Allocate memory for N elements of S bytes, with error checking,
102 and zero it. */
104 void *
105 xcalloc (size_t n, size_t s)
107 void *p;
109 p = calloc (n, s);
110 if (p == NULL)
111 p = fixup_null_alloc (n);
112 return p;
115 /* Change the size of an allocated block of memory P to N bytes,
116 with error checking.
117 If P is NULL, run xmalloc. */
119 void *
120 xrealloc (void *p, size_t n)
122 if (p == NULL)
123 return xmalloc (n);
124 p = realloc (p, n);
125 if (p == NULL)
126 p = fixup_null_alloc (n);
127 return p;