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 unchecked integer overflow when calculating array sizes,
18 fail to check the return value of @code{malloc} and @code{realloc} for
21 forget to fully initialize memory just allocated with @code{malloc},
23 duplicate calls to @code{free} by forgetting to set the pointer
24 variable to @code{NULL},
26 leaking memory in calls to @code{realloc} when that call fails.
29 The @code{safe-alloc} module addresses these problems in the following way:
33 It defines macros that wrap around the standard C allocation
34 functions. That makes it possible to use the compiler's knowledge of
35 the size of objects for allocation; it also allows setting pointers
36 passed in as arguments when appropriate.
38 It uses return values only for a success/failure error condition flag,
39 and annotates them with GCC's @code{__warn_unused_result__} attribute.
41 When allocating a fresh array, it uses @code{calloc} instead of
42 @code{malloc} so that the array's contents are zeroed.
43 However, memory added to an already-existing array is uninitialized.
46 @defmac {int} ALLOC (ptr)
48 Allocate @code{sizeof *ptr} bytes of memory and store the address of
49 allocated memory in @code{ptr}. Fill the newly allocated memory with
52 Returns @minus{}1 on failure, 0 on success.
55 @defmac {int} ALLOC_N (ptr, count)
57 Allocate an array of @code{count} elements, each @code{sizeof *ptr}
58 bytes long, and store the address of allocated memory in
59 @code{ptr}. Fill the newly allocated memory with zeros.
61 Returns @minus{}1 on failure, 0 on success.
64 @defmac {int} ALLOC_N_UNINITIALIZED (ptr, count)
65 @findex ALLOC_N_UNINITIALIZED
66 Allocate an array of @code{count} elements, each @code{sizeof *ptr}
67 bytes long, and store the address of allocated memory in
68 @code{ptr}. The allocated memory is not initialized.
70 Returns @minus{}1 on failure, 0 on success.
73 @defmac {int} REALLOC_N (ptr, count)
75 Reallocate the memory pointed to by @code{ptr} to be big enough to hold
76 at least @code{count} elements, each @code{sizeof *ptr} bytes long,
77 and store the address of allocated memory in @code{ptr}. If
78 reallocation fails, the @code{ptr} variable is not modified.
79 If the new array is smaller than the old one, discard excess contents;
80 if larger, the newly added storage is not initialized.
82 Returns @minus{}1 on failure, 0 on success.
85 @defmac {void} FREE (ptr)
87 Free the memory stored in @code{ptr} and set @code{ptr} to