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