Dynamic Memory Allocation

The following interfaces are used most often:

  • malloc() – Returns a pointer to a block of memory at least as large as the amount of memory that is requested. The block is aligned to store any type of data. For more information, see the malloc(3C) man page.

  • free() – Returns the memory that is obtained from malloc(), calloc(), realloc(), memalign(), or valloc() to system memory. Trying to free a block that was not reserved by a dynamic memory allocation interface is an error and causes a process to crash. For more information, see the free(3C) man page.

  • calloc() – Returns a pointer to a block of memory that is initialized to zeros. Memory reserved by calloc() can be returned to the system through either watchmalloc() or free(). The memory is allocated and aligned to contain an array of a specified number of elements of a specified size. For more information, see the calloc(3C) man page.

Other dynamic memory allocation interfaces are as follows:

  • malloc_usable_size(void *ptr) – Enables callers to obtain the usable number of bytes in a block of memory returned by malloc(). See the malloc-usable-size(3C) man page.

  • memalign() – Allocates a specified number of bytes on a specified alignment boundary. The alignment boundary must be a power of 2. For more information, see the memalign(3C) man page.

  • realloc() – Changes the size of the memory block allocated to a process. realloc() can be used to increase or reduce the size of an allocated block of memory. realloc() is the only way to shrink a memory allocation without causing a problem. The location in memory of the reallocated block might be changed, but the contents up to the point of the allocation size change remain the same. For more information, see the realloc(3C) man page.

  • void *reallocarray(void *ptr, size_t nmemb, size_t size); – Enables callers to rely on libc to do overflow checking for the nmemb * size calculation, rather than the caller needing to do overflow checking. The routine can also be used for new memory allocations by passing NULL for the ptr argument. This behavior is similar to calloc() without zero'ing the allocated memory. For more information, see the reallocarray(3C) man page.

  • reallocf() – Changes the size of an allocated memory block. Unlike realloc(), if this function cannot allocate the requested size, it frees the existing block, so that programs do not have to keep track of the old address and free it themselves. For more information, see the reallocf(3C) man page.

  • valloc() – Allocates a specified number of bytes that are aligned on a page boundary. For more information, see the valloc(3C) man page.