Consistent macro naming for macros that use GCC __attribute__.
[gnulib.git] / lib / xalloc.h
1 /* xalloc.h -- malloc with out-of-memory checking
2
3    Copyright (C) 1990-2000, 2003-2004, 2006-2011 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 <http://www.gnu.org/licenses/>.  */
17
18 #ifndef XALLOC_H_
19 # define XALLOC_H_
20
21 # include <stddef.h>
22
23
24 # ifdef __cplusplus
25 extern "C" {
26 # endif
27
28
29 # if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 8)
30 #  define _GL_ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
31 # else
32 #  define _GL_ATTRIBUTE_NORETURN /* empty */
33 # endif
34
35 # if __GNUC__ >= 3
36 #  define _GL_ATTRIBUTE_MALLOC __attribute__ ((__malloc__))
37 # else
38 #  define _GL_ATTRIBUTE_MALLOC
39 # endif
40
41 # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
42 #  define _GL_ATTRIBUTE_ALLOC_SIZE(args) __attribute__ ((__alloc_size__ args))
43 # else
44 #  define _GL_ATTRIBUTE_ALLOC_SIZE(args)
45 # endif
46
47 /* This function is always triggered when memory is exhausted.
48    It must be defined by the application, either explicitly
49    or by using gnulib's xalloc-die module.  This is the
50    function to call when one wants the program to die because of a
51    memory allocation failure.  */
52 extern void xalloc_die (void) _GL_ATTRIBUTE_NORETURN;
53
54 void *xmalloc (size_t s)
55       _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
56 void *xzalloc (size_t s)
57       _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
58 void *xcalloc (size_t n, size_t s)
59       _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1, 2));
60 void *xrealloc (void *p, size_t s)
61       _GL_ATTRIBUTE_ALLOC_SIZE ((2));
62 void *x2realloc (void *p, size_t *pn);
63 void *xmemdup (void const *p, size_t s)
64       _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((2));
65 char *xstrdup (char const *str)
66       _GL_ATTRIBUTE_MALLOC;
67
68 /* Return 1 if an array of N objects, each of size S, cannot exist due
69    to size arithmetic overflow.  S must be positive and N must be
70    nonnegative.  This is a macro, not an inline function, so that it
71    works correctly even when SIZE_MAX < N.
72
73    By gnulib convention, SIZE_MAX represents overflow in size
74    calculations, so the conservative dividend to use here is
75    SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
76    However, malloc (SIZE_MAX) fails on all known hosts where
77    sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
78    exactly-SIZE_MAX allocations on such hosts; this avoids a test and
79    branch when S is known to be 1.  */
80 # define xalloc_oversized(n, s) \
81     ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
82
83
84 /* In the following macros, T must be an elementary or structure/union or
85    typedef'ed type, or a pointer to such a type.  To apply one of the
86    following macros to a function pointer or array type, you need to typedef
87    it first and use the typedef name.  */
88
89 /* Allocate an object of type T dynamically, with error checking.  */
90 /* extern t *XMALLOC (typename t); */
91 # define XMALLOC(t) ((t *) xmalloc (sizeof (t)))
92
93 /* Allocate memory for N elements of type T, with error checking.  */
94 /* extern t *XNMALLOC (size_t n, typename t); */
95 # define XNMALLOC(n, t) \
96     ((t *) (sizeof (t) == 1 ? xmalloc (n) : xnmalloc (n, sizeof (t))))
97
98 /* Allocate an object of type T dynamically, with error checking,
99    and zero it.  */
100 /* extern t *XZALLOC (typename t); */
101 # define XZALLOC(t) ((t *) xzalloc (sizeof (t)))
102
103 /* Allocate memory for N elements of type T, with error checking,
104    and zero it.  */
105 /* extern t *XCALLOC (size_t n, typename t); */
106 # define XCALLOC(n, t) \
107     ((t *) (sizeof (t) == 1 ? xzalloc (n) : xcalloc (n, sizeof (t))))
108
109
110 # if HAVE_INLINE
111 #  define static_inline static inline
112 # else
113 void *xnmalloc (size_t n, size_t s)
114       _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1, 2));
115 void *xnrealloc (void *p, size_t n, size_t s)
116       _GL_ATTRIBUTE_ALLOC_SIZE ((2, 3));
117 void *x2nrealloc (void *p, size_t *pn, size_t s);
118 char *xcharalloc (size_t n)
119       _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
120 # endif
121
122 # ifdef static_inline
123
124 /* Allocate an array of N objects, each with S bytes of memory,
125    dynamically, with error checking.  S must be nonzero.  */
126
127 static_inline void *xnmalloc (size_t n, size_t s)
128                     _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1, 2));
129 static_inline void *
130 xnmalloc (size_t n, size_t s)
131 {
132   if (xalloc_oversized (n, s))
133     xalloc_die ();
134   return xmalloc (n * s);
135 }
136
137 /* Change the size of an allocated block of memory P to an array of N
138    objects each of S bytes, with error checking.  S must be nonzero.  */
139
140 static_inline void *xnrealloc (void *p, size_t n, size_t s)
141                     _GL_ATTRIBUTE_ALLOC_SIZE ((2, 3));
142 static_inline void *
143 xnrealloc (void *p, size_t n, size_t s)
144 {
145   if (xalloc_oversized (n, s))
146     xalloc_die ();
147   return xrealloc (p, n * s);
148 }
149
150 /* If P is null, allocate a block of at least *PN such objects;
151    otherwise, reallocate P so that it contains more than *PN objects
152    each of S bytes.  *PN must be nonzero unless P is null, and S must
153    be nonzero.  Set *PN to the new number of objects, and return the
154    pointer to the new block.  *PN is never set to zero, and the
155    returned pointer is never null.
156
157    Repeated reallocations are guaranteed to make progress, either by
158    allocating an initial block with a nonzero size, or by allocating a
159    larger block.
160
161    In the following implementation, nonzero sizes are increased by a
162    factor of approximately 1.5 so that repeated reallocations have
163    O(N) overall cost rather than O(N**2) cost, but the
164    specification for this function does not guarantee that rate.
165
166    Here is an example of use:
167
168      int *p = NULL;
169      size_t used = 0;
170      size_t allocated = 0;
171
172      void
173      append_int (int value)
174        {
175          if (used == allocated)
176            p = x2nrealloc (p, &allocated, sizeof *p);
177          p[used++] = value;
178        }
179
180    This causes x2nrealloc to allocate a block of some nonzero size the
181    first time it is called.
182
183    To have finer-grained control over the initial size, set *PN to a
184    nonzero value before calling this function with P == NULL.  For
185    example:
186
187      int *p = NULL;
188      size_t used = 0;
189      size_t allocated = 0;
190      size_t allocated1 = 1000;
191
192      void
193      append_int (int value)
194        {
195          if (used == allocated)
196            {
197              p = x2nrealloc (p, &allocated1, sizeof *p);
198              allocated = allocated1;
199            }
200          p[used++] = value;
201        }
202
203    */
204
205 static_inline void *
206 x2nrealloc (void *p, size_t *pn, size_t s)
207 {
208   size_t n = *pn;
209
210   if (! p)
211     {
212       if (! n)
213         {
214           /* The approximate size to use for initial small allocation
215              requests, when the invoking code specifies an old size of
216              zero.  64 bytes is the largest "small" request for the
217              GNU C library malloc.  */
218           enum { DEFAULT_MXFAST = 64 };
219
220           n = DEFAULT_MXFAST / s;
221           n += !n;
222         }
223     }
224   else
225     {
226       /* Set N = ceil (1.5 * N) so that progress is made if N == 1.
227          Check for overflow, so that N * S stays in size_t range.
228          The check is slightly conservative, but an exact check isn't
229          worth the trouble.  */
230       if ((size_t) -1 / 3 * 2 / s <= n)
231         xalloc_die ();
232       n += (n + 1) / 2;
233     }
234
235   *pn = n;
236   return xrealloc (p, n * s);
237 }
238
239 /* Return a pointer to a new buffer of N bytes.  This is like xmalloc,
240    except it returns char *.  */
241
242 static_inline char *xcharalloc (size_t n)
243                     _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
244 static_inline char *
245 xcharalloc (size_t n)
246 {
247   return XNMALLOC (n, char);
248 }
249
250 # endif
251
252 # ifdef __cplusplus
253 }
254
255 /* C++ does not allow conversions from void * to other pointer types
256    without a cast.  Use templates to work around the problem when
257    possible.  */
258
259 template <typename T> inline T *
260 xrealloc (T *p, size_t s)
261 {
262   return (T *) xrealloc ((void *) p, s);
263 }
264
265 template <typename T> inline T *
266 xnrealloc (T *p, size_t n, size_t s)
267 {
268   return (T *) xnrealloc ((void *) p, n, s);
269 }
270
271 template <typename T> inline T *
272 x2realloc (T *p, size_t *pn)
273 {
274   return (T *) x2realloc ((void *) p, pn);
275 }
276
277 template <typename T> inline T *
278 x2nrealloc (T *p, size_t *pn, size_t s)
279 {
280   return (T *) x2nrealloc ((void *) p, pn, s);
281 }
282
283 template <typename T> inline T *
284 xmemdup (T const *p, size_t s)
285 {
286   return (T *) xmemdup ((void const *) p, s);
287 }
288
289 # endif
290
291
292 #endif /* !XALLOC_H_ */