(Checked realloc with overflow protection)


#include <tap/basic.h>

void *breallocarray(void *ptr, size_t n, size_t size);


breallocarray() is a wrapper around realloc() that checks whether the memory allocation succeed, returning the newly allocated memory on success and calling sysbail() on failure. It takes a count and a per-element size, the same as calloc(), instead of a simple size, and checks internally for integer overflow when doing the allocation. It is intended for use inside TAP test cases where the test case should be aborted if memory allocation fails, and avoid the need to check each allocation as it's performed.

This function is inspired by the OpenBSD reallocarray() function, but does its own range checking rather than relying on a system reallocarray() function.


breallocarray() returns a pointer to the reallocated memory (which may or may not be the same as ptr), the same as the standard realloc() function. It will never return NULL; if memory allocation fails, it will abort the program.


breallocarray() will not allocate more than UINT_MAX bytes rather than SIZE_MAX bytes, since the C TAP Harness library only assumes ISO C89 and SUSv3 and therefore cannot assume stdint.h exists or that SIZE_MAX is defined. This is unlikely to cause issues in practice. This constraint will be relaxed when assuming ISO C99 is somewhat safer.


Russ Allbery <>


Copyright 2014 Russ Allbery <>

Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty.

SPDX-License-Identifier: FSFAP


brealloc(3), realloc(3), reallocarray(3), sysbail(3)

The current version of the C TAP Harness library is available from its web page at <>.

Last modified and spun 2018-05-06