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 themalloc
(3C) man page. -
free
() – Returns the memory that is obtained frommalloc
(),calloc
(),realloc
(),memalign
(), orvalloc
() 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 thefree
(3C) man page. -
calloc
() – Returns a pointer to a block of memory that is initialized to zeros. Memory reserved bycalloc
() can be returned to the system through eitherwatchmalloc
() orfree
(). The memory is allocated and aligned to contain an array of a specified number of elements of a specified size. For more information, see thecalloc
(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 bymalloc
(). See themalloc-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 thememalign
(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 therealloc
(3C) man page. -
void *reallocarray(void *ptr, size_t nmemb, size_t size);
– Enables callers to rely onlibc
to do overflow checking for thenmemb *
size calculation, rather than the caller needing to do overflow checking. The routine can also be used for new memory allocations by passingNULL
for theptr
argument. This behavior is similar tocalloc
() without zero'ing the allocated memory. For more information, see thereallocarray
(3C) man page. -
reallocf
() – Changes the size of an allocated memory block. Unlikerealloc
(), 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 thereallocf
(3C) man page. -
valloc
() – Allocates a specified number of bytes that are aligned on a page boundary. For more information, see thevalloc
(3C) man page.