

OpenBSD's reallocarray extension - brynet

reallocarray(3) is a malloc(3)&#x2F;realloc(3) extension from OpenBSD, it is very portable and easy to incorporate into existing codebases.<p>The intention of reallocarray to replace the following idiom:<p><pre><code>    if ((p = malloc(num * size)) == NULL)
        err(1, &quot;malloc&quot;);
</code></pre>
..with the much safer:<p><pre><code>    if ((p = reallocarray(NULL, num, size)) == NULL)
        err(1, &quot;malloc&quot;);
</code></pre>
In the first example, num * size may lead to an undetected integer multiplication overflow.<p>reallocarray(3) performs the same overflow detection that is conventionally done by calloc(3), but without the expensive memory zeroing operation. It returns NULL on overflow, with errno set to ENOMEM, as is permitted by standards.<p>It is now being used extensively by LibreSSL as within OpenBSD&#x27;s own userland; and in the kernel, as mallocarray(9).
======
brynet
[http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-
current/man3/...](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-
current/man3/reallocarray.3)

[http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-
current/man9/...](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-
current/man9/mallocarray.9)

[http://cvsweb.openbsd.org/cgi-
bin/cvsweb/~checkout~/src/lib/...](http://cvsweb.openbsd.org/cgi-
bin/cvsweb/~checkout~/src/lib/libc/stdlib/reallocarray.c?content-
type=text/plain)

