reallocarr(3) - NetBSD Manual Pages

Command: Section: Arch: Collection:  
REALLOCARR(3)           NetBSD Library Functions Manual          REALLOCARR(3)


NAME
reallocarr -- reallocate array
SYNOPSIS
#include <stdlib.h> int reallocarr(void *ptrp, size_t number, size_t size);
DESCRIPTION
The reallocarr function safely allocates, resizes, or frees arrays in memory. If ptr is a null pointer, or a pointer to memory previously allocated with reallocarr, then reallocarr(&ptr, ,,number, ,, size) allocates or reallocates the memory that ptr points to, possibly moving it to a dif- ferent location in memory, so that it has space for an array of number elements of size bytes apiece. reallocarr updates ptr in case it was moved on success, and leaves it unchanged on failure. If ptr was previously allocated, the objects stored at ptr[0], ptr[1], ..., up to the shorter of its old number and its new number, are copied into the new memory, like realloc(3). ptr may be null and number may be zero. size must be nonzero. The memory allocated by reallocarr may be freed with reallocarr(&ptr, ,0, , size), which will always succeed and unconditionally set ptr to null. Like calloc(3), reallocarr fails gracefully if the product of number and size would overflow the representable size of memory. Unlike calloc(3), new memory allocated by reallocarr is not zero-initialized. The reallocarr function may alter errno as a side effect. Note that the argument ptrp is a pointer to a pointer to allocated mem- ory, unlike realloc(3) which takes a pointer to allocated memory.
RETURN VALUES
On successful completion, reallocarr returns 0 and updates ptr. Other- wise, an errno(2) is returned, and ptr and the memory it points to are unmodified.
EXAMPLES
The following uses reallocarr() to initialize an array of INITSIZE inte- gers, then resizes it to NEWSIZE elements, and finally frees it: int *data = NULL; int error = 0; /* allocate */ error = reallocarr(&data, INITSIZE, sizeof(*data)); if (error) errc(1, error, "reallocarr failed"); ... /* resize */ error = reallocarr(&data, NEWSIZE, sizeof(*data)); if (error) errc(1, error, "reallocarr failed on resize"); ... /* free */ (void)reallocarr(&data, 0, sizeof(*data)); assert(data == NULL);
SEE ALSO
calloc(3), realloc(3), reallocarray(3)
HISTORY
reallocarr first appeared in NetBSD 7.0. OpenBSD introduced the reallocarray(3) function for the same purpose, but the interface makes it difficult to correctly handle zero-sized allocations. NetBSD 10.99 August 31, 2022 NetBSD 10.99
Powered by man-cgi (2024-03-20). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.