## Memory Management

### FUNCTIONS

      void * alloc(long size);
      void * zero_alloc(long size);
      void * realloc(void *ptr, long newsize);
      void   free(void *ptr);
      void   debug_memory(int on);
      long   memory_used(void);

### NOTES

All memory allocation in the library uses the functions described in this section.

The alloc function allocates a block of memory `size` bytes in length. This is usually just a safe wrapper around the standard C function malloc, but may perform additional integrity checks. It aborts the program if it runs out of memory. Allocating a zero-sized block is valid and returns NULL.

Use free to release from memory any blocks allocated by alloc. Never use the standard C function free on a block. Passing NULL to free is allowed, and does nothing.

The zero_alloc function uses alloc to create a block of memory, and then uses the standard C function memset to set every byte of that block to the value zero. It returns NULL only if alloc returned NULL.

The realloc function accepts a pointer to a memory block which was previously allocated using alloc, and resizes it to the `newsize` (in bytes). It keeps the old contents, or as much as will fit in the new block if making it smaller. The block may be moved around in memory, so a new pointer is returned by this function, and the old pointer becomes invalid. If the function runs out of memory, it aborts the program. The block may be resized to zero bytes, in which case the function frees the block and returns NULL. The pointer passed in may be NULL, in which case it just calls alloc. This function is essentially a safe wrapper around the standard C function realloc, except that it operates only on blocks produced from alloc.

The debug_memory function activates or deactivates a memory debugger, which replaces internal calls to malloc, realloc and free with calls to custom, portable, debugging functions. Once activated by passing a non-zero integer to this function, debugging should not be deactivated, since this might cause blocks allocated using a custom allocator to be deallocated using the standard free function, which would cause a crash. The option to switch off memory debugging (by passing zero to debug_memory) exists because there are certain controlled conditions where it might be possible to do this.

The memory_used function attempts to report how many bytes are currently allocated by these memory functions. This will only be correct if the debugging mode was activated before any other library functions were called. If the debugging mode was never activated, the function reports how many bytes have been allocated through alloc only, ignoring changes made through calls to free or realloc.