Safe Allocation Macros
======================

The standard C library malloc/realloc/calloc/free APIs are prone to a number of common coding errors.  The safe-alloc module provides macros that make it easier to avoid many of them.  It still uses the standard C allocation functions behind the scenes.

Some of the memory allocation mistakes that are commonly made are

  * passing the incorrect number of bytes to malloc, especially when allocating an array,

  * unchecked integer overflow when calculating array sizes,

  * fail to check the return value of malloc and realloc for errors,

  * forget to fully initialize memory just allocated with malloc,

  * duplicate calls to free by forgetting to set the pointer variable to NULL,

  * leaking memory in calls to realloc when that call fails.

The safe-alloc module addresses these problems in the following way:

  * It defines macros that wrap around the standard C allocation functions.  That makes it possible to use the compiler's knowledge of the size of objects for allocation; it also allows setting pointers passed in as arguments when appropriate.

  * It uses return values only for a success/failure error condition flag, and annotates them with GCC's __warn_unused_result__ attribute.

  * When allocating a fresh array, it uses calloc instead of malloc so that the array's contents are zeroed. However, memory added to an already-existing array is uninitialized.

 -- Macro: int ALLOC (ptr)
     Allocate sizeof *ptr bytes of memory and store the address of allocated memory in ptr.  Fill the newly allocated memory with zeros.

     Returns -1 on failure, 0 on success.

 -- Macro: int ALLOC_N (ptr, count)
     Allocate an array of count elements, each sizeof *ptr bytes long, and store the address of allocated memory in ptr.  Fill the newly allocated memory with zeros.

     Returns -1 on failure, 0 on success.

 -- Macro: int ALLOC_N_UNINITIALIZED (ptr, count)
     Allocate an array of count elements, each sizeof *ptr bytes long, and store the address of allocated memory in ptr.  The allocated memory is not initialized.

     Returns -1 on failure, 0 on success.

 -- Macro: int REALLOC_N (ptr, count)
     Reallocate the memory pointed to by ptr to be big enough to hold at least count elements, each sizeof *ptr bytes long, and store the address of allocated memory in ptr.  If reallocation fails, the ptr variable is not modified. If the new array is smaller than the old one, discard excess contents; if larger, the newly added storage is not initialized.

     Returns -1 on failure, 0 on success.

 -- Macro: void FREE (ptr)
     Free the memory stored in ptr and set ptr to NULL.