1 @node Safe Allocation Macros
2 @section Safe Allocation Macros
4 The standard C library malloc/realloc/calloc/free APIs are prone to a
5 number of common coding errors. The @code{safe-alloc} module provides
6 macros that make it easier to avoid many of them. It still uses the
7 standard C allocation functions behind the scenes.
9 Some of the memory allocation mistakes that are commonly made are
13 passing the incorrect number of bytes to @code{malloc}, especially
14 when allocating an array,
16 fail to check the return value of @code{malloc} and @code{realloc} for
19 forget to fully initialize memory just allocated with @code{malloc},
21 duplicate calls to @code{free} by forgetting to set the pointer
22 variable to @code{NULL},
24 leaking memory in calls to @code{realloc} when that call fails.
27 The @code{safe-alloc} module addresses these problems in the following way:
31 It defines macros that wrap around the standard C allocation
32 functions. That makes it possible to use the compiler's knowledge of
33 the size of objects for allocation; it also allows setting pointers
34 passed in as arguments when appropriate.
36 It uses return values only for a success/failure error condition flag,
37 and annotates them with GCC's @code{__warn_unused_result__} attribute.
39 It uses @code{calloc} instead of @code{malloc}.
42 @defmac {int} ALLOC (ptr)
44 Allocate @code{sizeof(*ptr)} bytes of memory and store the address of
45 allocated memory in @code{ptr}. Fill the newly allocated memory with
48 Returns @minus{}1 on failure, 0 on success.
51 @defmac {int} ALLOC_N (ptr, count)
53 Allocate an array of @code{count} elements, each @code{sizeof(*ptr)}
54 bytes long, and store the address of allocated memory in
55 @code{ptr}. Fill the newly allocated memory with zeros.
57 Returns @minus{}1 on failure, 0 on success.
60 @defmac {int} ALLOC_N_UNINITIALIZED (ptr, count)
61 @findex ALLOC_N_UNINITIALIZED
62 Allocate an array of @code{count} elements, each @code{sizeof(*ptr)}
63 bytes long, and store the address of allocated memory in
64 @code{ptr}. The allocated memory is not initialized.
66 Returns @minus{}1 on failure, 0 on success.
69 @defmac {int} REALLOC_N (ptr, count)
71 Reallocate the memory pointed to by @code{ptr} to be big enough to hold
72 at least @code{count} elements, each @code{sizeof(*ptr)} bytes long,
73 and store the address of allocated memory in @code{ptr}. If
74 reallocation fails, the @code{ptr} variable is not modified.
76 Returns @minus{}1 on failure, 0 on success.
79 @defmac {void} FREE (ptr)
81 Free the memory stored in @code{ptr} and set @code{ptr} to