Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Contact Us
Online Help
Domain Status
Man Pages

Virtual Servers

Topology Map

Server Agreement
Year 2038

USA Flag



Man Pages
REALLOCARRAY(3) FreeBSD Library Functions Manual REALLOCARRAY(3)

memory reallocation function

Standard C Library (libc, -lc)

#include <stdlib.h>

void *
reallocarray(void *ptr, size_t nmemb, size_t size);

The reallocarray() 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.

The reallocarray() function returns a pointer to the allocated space; otherwise, a NULL pointer is returned and errno is set to ENOMEM.

Consider reallocarray() 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 reallocarray():

if ((p = reallocarray(NULL, num, size)) == NULL)
	err(1, "reallocarray");

When using realloc(), be careful to avoid the following idiom:

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 NULL indicates that the old object still remains allocated. Better code looks like this:

newsize = size + 50;
if ((newp = realloc(p, newsize)) == NULL) {
	p = NULL;
	size = 0;
	return (NULL);
p = newp;
size = newsize;

As with malloc(), it is important to ensure the new size value will not overflow; i.e. avoid allocations like the following:

if ((newp = realloc(p, num * size)) == NULL) {

Instead, use reallocarray():

if ((newp = reallocarray(p, num, size)) == NULL) {


The reallocarray() function first appeared in OpenBSD 5.6 and FreeBSD 11.0.
May 1, 2015 FreeBSD 13.1-RELEASE

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.