|
NAMEreallocarray —
memory reallocation function
LIBRARYStandard C Library (libc, -lc)SYNOPSIS#include <stdlib.h>
void *
DESCRIPTIONThereallocarray () function is similar to the
realloc () function except it operates on
nmemb members of size size and
checks for integer overflow in the calculation nmemb *
size.
RETURN VALUESThereallocarray () function returns a pointer to the
allocated space; otherwise, a NULL pointer is returned
and errno is set to ENOMEM .
EXAMPLESConsiderreallocarray () when there is multiplication in
the size argument of malloc () or
realloc (). For example, avoid this common idiom as it
may lead to integer overflow:
if ((p = malloc(num * size)) == NULL) err(1, "malloc"); A drop-in replacement is the OpenBSD
extension if ((p = reallocarray(NULL, num, size)) == NULL) err(1, "reallocarray"); When using size += 50; if ((p = realloc(p, size)) == NULL) return (NULL); Do not adjust the variable describing how much memory has been
allocated until the allocation has been successful. This can cause aberrant
program behavior if the incorrect size value is used. In most cases, the
above sample will also result in a leak of memory. As stated earlier, a
return value of newsize = size + 50; if ((newp = realloc(p, newsize)) == NULL) { free(p); p = NULL; size = 0; return (NULL); } p = newp; size = newsize; As with if ((newp = realloc(p, num * size)) == NULL) { ... Instead, use if ((newp = reallocarray(p, num, size)) == NULL) { ... SEE ALSOrealloc(3)HISTORYThereallocarray () function first appeared in
OpenBSD 5.6 and FreeBSD 11.0.
Visit the GSP FreeBSD Man Page Interface. |