1*09a3aaf3SDag-Erling Smørgrav /* $OpenBSD: reallocarray.c,v 1.1 2014/05/08 21:43:49 deraadt Exp $ */ 2*09a3aaf3SDag-Erling Smørgrav /* 3*09a3aaf3SDag-Erling Smørgrav * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> 4*09a3aaf3SDag-Erling Smørgrav * 5*09a3aaf3SDag-Erling Smørgrav * Permission to use, copy, modify, and distribute this software for any 6*09a3aaf3SDag-Erling Smørgrav * purpose with or without fee is hereby granted, provided that the above 7*09a3aaf3SDag-Erling Smørgrav * copyright notice and this permission notice appear in all copies. 8*09a3aaf3SDag-Erling Smørgrav * 9*09a3aaf3SDag-Erling Smørgrav * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10*09a3aaf3SDag-Erling Smørgrav * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11*09a3aaf3SDag-Erling Smørgrav * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12*09a3aaf3SDag-Erling Smørgrav * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13*09a3aaf3SDag-Erling Smørgrav * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14*09a3aaf3SDag-Erling Smørgrav * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15*09a3aaf3SDag-Erling Smørgrav * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16*09a3aaf3SDag-Erling Smørgrav */ 17*09a3aaf3SDag-Erling Smørgrav 18*09a3aaf3SDag-Erling Smørgrav #include "config.h" 19*09a3aaf3SDag-Erling Smørgrav #include <sys/types.h> 20*09a3aaf3SDag-Erling Smørgrav #include <errno.h> 21*09a3aaf3SDag-Erling Smørgrav #include <stdint.h> 22*09a3aaf3SDag-Erling Smørgrav #include <stdlib.h> 23*09a3aaf3SDag-Erling Smørgrav 24*09a3aaf3SDag-Erling Smørgrav /* 25*09a3aaf3SDag-Erling Smørgrav * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX 26*09a3aaf3SDag-Erling Smørgrav * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW 27*09a3aaf3SDag-Erling Smørgrav */ 28*09a3aaf3SDag-Erling Smørgrav #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) 29*09a3aaf3SDag-Erling Smørgrav 30*09a3aaf3SDag-Erling Smørgrav void * 31*09a3aaf3SDag-Erling Smørgrav reallocarray(void *optr, size_t nmemb, size_t size) 32*09a3aaf3SDag-Erling Smørgrav { 33*09a3aaf3SDag-Erling Smørgrav if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 34*09a3aaf3SDag-Erling Smørgrav nmemb > 0 && SIZE_MAX / nmemb < size) { 35*09a3aaf3SDag-Erling Smørgrav errno = ENOMEM; 36*09a3aaf3SDag-Erling Smørgrav return NULL; 37*09a3aaf3SDag-Erling Smørgrav } 38*09a3aaf3SDag-Erling Smørgrav return realloc(optr, size * nmemb); 39*09a3aaf3SDag-Erling Smørgrav } 40