* lib/xalloc.h (xnmalloc, xnrealloc, x2nrealloc): Now static
[gnulib.git] / lib / xalloc.h
1 /* xalloc.h -- malloc with out-of-memory checking
2
3    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
4    1999, 2000, 2003, 2004, 2006 Free Software Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 #ifndef XALLOC_H_
21 # define XALLOC_H_
22
23 # include <stddef.h>
24
25
26 # ifdef __cplusplus
27 extern "C" {
28 # endif
29
30
31 # ifndef __attribute__
32 #  if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
33 #   define __attribute__(x)
34 #  endif
35 # endif
36
37 # ifndef ATTRIBUTE_NORETURN
38 #  define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
39 # endif
40
41 /* This function is always triggered when memory is exhausted.
42    It must be defined by the application, either explicitly
43    or by using gnulib's xalloc-die module.  This is the
44    function to call when one wants the program to die because of a
45    memory allocation failure.  */
46 extern void xalloc_die (void) ATTRIBUTE_NORETURN;
47
48 void *xmalloc (size_t s);
49 void *xzalloc (size_t s);
50 void *xcalloc (size_t n, size_t s);
51 void *xrealloc (void *p, size_t s);
52 void *x2realloc (void *p, size_t *pn);
53 void *xmemdup (void const *p, size_t s);
54 char *xstrdup (char const *str);
55
56 /* Return 1 if an array of N objects, each of size S, cannot exist due
57    to size arithmetic overflow.  S must be positive and N must be
58    nonnegative.  This is a macro, not an inline function, so that it
59    works correctly even when SIZE_MAX < N.
60
61    By gnulib convention, SIZE_MAX represents overflow in size
62    calculations, so the conservative dividend to use here is
63    SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
64    However, malloc (SIZE_MAX) fails on all known hosts where
65    sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
66    exactly-SIZE_MAX allocations on such hosts; this avoids a test and
67    branch when S is known to be 1.  */
68 # define xalloc_oversized(n, s) \
69     ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
70
71 /* Allocate an array of N objects, each with S bytes of memory,
72    dynamically, with error checking.  S must be nonzero.  */
73
74 static inline void *
75 xnmalloc (size_t n, size_t s)
76 {
77   if (xalloc_oversized (n, s))
78     xalloc_die ();
79   return xmalloc (n * s);
80 }
81
82 /* Change the size of an allocated block of memory P to an array of N
83    objects each of S bytes, with error checking.  S must be nonzero.  */
84
85 static inline void *
86 xnrealloc (void *p, size_t n, size_t s)
87 {
88   if (xalloc_oversized (n, s))
89     xalloc_die ();
90   return xrealloc (p, n * s);
91 }
92
93 /* If P is null, allocate a block of at least *PN such objects;
94    otherwise, reallocate P so that it contains more than *PN objects
95    each of S bytes.  *PN must be nonzero unless P is null, and S must
96    be nonzero.  Set *PN to the new number of objects, and return the
97    pointer to the new block.  *PN is never set to zero, and the
98    returned pointer is never null.
99
100    Repeated reallocations are guaranteed to make progress, either by
101    allocating an initial block with a nonzero size, or by allocating a
102    larger block.
103
104    In the following implementation, nonzero sizes are doubled so that
105    repeated reallocations have O(N log N) overall cost rather than
106    O(N**2) cost, but the specification for this function does not
107    guarantee that sizes are doubled.
108
109    Here is an example of use:
110
111      int *p = NULL;
112      size_t used = 0;
113      size_t allocated = 0;
114
115      void
116      append_int (int value)
117        {
118          if (used == allocated)
119            p = x2nrealloc (p, &allocated, sizeof *p);
120          p[used++] = value;
121        }
122
123    This causes x2nrealloc to allocate a block of some nonzero size the
124    first time it is called.
125
126    To have finer-grained control over the initial size, set *PN to a
127    nonzero value before calling this function with P == NULL.  For
128    example:
129
130      int *p = NULL;
131      size_t used = 0;
132      size_t allocated = 0;
133      size_t allocated1 = 1000;
134
135      void
136      append_int (int value)
137        {
138          if (used == allocated)
139            {
140              p = x2nrealloc (p, &allocated1, sizeof *p);
141              allocated = allocated1;
142            }
143          p[used++] = value;
144        }
145
146    */
147
148 static inline void *
149 x2nrealloc (void *p, size_t *pn, size_t s)
150 {
151   size_t n = *pn;
152
153   if (! p)
154     {
155       if (! n)
156         {
157           /* The approximate size to use for initial small allocation
158              requests, when the invoking code specifies an old size of
159              zero.  64 bytes is the largest "small" request for the
160              GNU C library malloc.  */
161           enum { DEFAULT_MXFAST = 64 };
162
163           n = DEFAULT_MXFAST / s;
164           n += !n;
165         }
166     }
167   else
168     {
169       if (((size_t) -1) / 2 / s < n)
170         xalloc_die ();
171       n *= 2;
172     }
173
174   *pn = n;
175   return xrealloc (p, n * s);
176 }
177
178 /* In the following macros, T must be an elementary or structure/union or
179    typedef'ed type, or a pointer to such a type.  To apply one of the
180    following macros to a function pointer or array type, you need to typedef
181    it first and use the typedef name.  */
182
183 /* Allocate an object of type T dynamically, with error checking.  */
184 /* extern t *XMALLOC (typename t); */
185 #define XMALLOC(t) ((t *) xmalloc (sizeof (t)))
186
187 /* Allocate memory for N elements of type T, with error checking.  */
188 /* extern t *XNMALLOC (size_t n, typename t); */
189 #define XNMALLOC(n, t) ((t *) xnmalloc (n, sizeof (t)))
190
191 /* Allocate an object of type T dynamically, with error checking,
192    and zero it.  */
193 /* extern t *XZALLOC (typename t); */
194 #define XZALLOC(t) ((t *) xzalloc (sizeof (t)))
195
196 /* Allocate memory for N elements of type T, with error checking,
197    and zero it.  */
198 /* extern t *XCALLOC (size_t n, typename t); */
199 #define XCALLOC(n, t) ((t *) xcalloc (n, sizeof (t)))
200
201 /* Return a pointer to a new buffer of N bytes.  This is like xmalloc,
202    except it returns char *.  */
203 static inline char *
204 xcharalloc (size_t n)
205 {
206   return XNMALLOC (n, char);
207 }
208
209 # ifdef __cplusplus
210 }
211
212 /* C++ does not allow conversions from void * to other pointer types
213    without a cast.  Use templates to work around the problem when
214    possible.  */
215
216 template <typename T> inline T *
217 xrealloc (T *p, size_t s)
218 {
219   return (T *) xrealloc ((void *) p, s);
220 }
221
222 template <typename T> inline T *
223 xnrealloc (T *p, size_t n, size_t s)
224 {
225   return (T *) xnrealloc ((void *) p, n, s);
226 }
227
228 template <typename T> inline T *
229 x2realloc (T *p, size_t *pn)
230 {
231   return (T *) x2realloc ((void *) p, pn);
232 }
233
234 template <typename T> inline T *
235 x2nrealloc (T *p, size_t *pn, size_t s)
236 {
237   return (T *) x2nrealloc ((void *) p, pn, s);
238 }
239
240 template <typename T> inline T *
241 xmemdup (T const *p, size_t s)
242 {
243   return (T *) xmemdup ((void const *) p, s);
244 }
245
246 # endif
247
248
249 #endif /* !XALLOC_H_ */