1 | /* xmalloc.c -- malloc with out of memory checking |
2 | Copyright (C) 1990-2022 Free Software Foundation, Inc. |
3 | This file is part of the GNU C Library. |
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 |
7 | by the Free Software Foundation; version 2 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 | #ifdef HAVE_CONFIG_H |
19 | #include <config.h> |
20 | #endif |
21 | |
22 | #define VOID void |
23 | |
24 | #include <sys/types.h> |
25 | |
26 | #if STDC_HEADERS || _LIBC |
27 | #include <stdlib.h> |
28 | static VOID *fixup_null_alloc (size_t n) __THROW; |
29 | VOID *xmalloc (size_t n) __THROW; |
30 | VOID *xcalloc (size_t n, size_t s) __THROW; |
31 | VOID *xrealloc (VOID *p, size_t n) __THROW; |
32 | #else |
33 | VOID *calloc (); |
34 | VOID *malloc (); |
35 | VOID *realloc (); |
36 | void free (); |
37 | #endif |
38 | |
39 | #include <libintl.h> |
40 | #include "error.h" |
41 | |
42 | #ifndef _ |
43 | # define _(str) gettext (str) |
44 | #endif |
45 | |
46 | #ifndef EXIT_FAILURE |
47 | #define EXIT_FAILURE 4 |
48 | #endif |
49 | |
50 | /* Exit value when the requested amount of memory is not available. |
51 | The caller may set it to some other value. */ |
52 | int xmalloc_exit_failure = EXIT_FAILURE; |
53 | |
54 | static VOID * |
55 | fixup_null_alloc (size_t n) |
56 | { |
57 | VOID *p; |
58 | |
59 | p = 0; |
60 | if (n == 0) |
61 | p = malloc ((size_t) 1); |
62 | if (p == 0) |
63 | error (xmalloc_exit_failure, 0, _("memory exhausted" )); |
64 | return p; |
65 | } |
66 | |
67 | /* Allocate N bytes of memory dynamically, with error checking. */ |
68 | |
69 | VOID * |
70 | xmalloc (size_t n) |
71 | { |
72 | VOID *p; |
73 | |
74 | p = malloc (n); |
75 | if (p == 0) |
76 | p = fixup_null_alloc (n); |
77 | return p; |
78 | } |
79 | |
80 | /* Allocate memory for N elements of S bytes, with error checking. */ |
81 | |
82 | VOID * |
83 | xcalloc (size_t n, size_t s) |
84 | { |
85 | VOID *p; |
86 | |
87 | p = calloc (n, s); |
88 | if (p == 0) |
89 | p = fixup_null_alloc (n); |
90 | return p; |
91 | } |
92 | |
93 | /* Change the size of an allocated block of memory P to N bytes, |
94 | with error checking. |
95 | If P is NULL, run xmalloc. */ |
96 | |
97 | VOID * |
98 | xrealloc (VOID *p, size_t n) |
99 | { |
100 | if (p == 0) |
101 | return xmalloc (n); |
102 | p = realloc (p, n); |
103 | if (p == 0) |
104 | p = fixup_null_alloc (n); |
105 | return p; |
106 | } |
107 | |