109a3aaf3SDag-Erling Smørgrav /* $OpenBSD: reallocarray.c,v 1.1 2014/05/08 21:43:49 deraadt Exp $ */ 209a3aaf3SDag-Erling Smørgrav /* 309a3aaf3SDag-Erling Smørgrav * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> 409a3aaf3SDag-Erling Smørgrav * 509a3aaf3SDag-Erling Smørgrav * Permission to use, copy, modify, and distribute this software for any 609a3aaf3SDag-Erling Smørgrav * purpose with or without fee is hereby granted, provided that the above 709a3aaf3SDag-Erling Smørgrav * copyright notice and this permission notice appear in all copies. 809a3aaf3SDag-Erling Smørgrav * 909a3aaf3SDag-Erling Smørgrav * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 1009a3aaf3SDag-Erling Smørgrav * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 1109a3aaf3SDag-Erling Smørgrav * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 1209a3aaf3SDag-Erling Smørgrav * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 1309a3aaf3SDag-Erling Smørgrav * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 1409a3aaf3SDag-Erling Smørgrav * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 1509a3aaf3SDag-Erling Smørgrav * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 1609a3aaf3SDag-Erling Smørgrav */ 1709a3aaf3SDag-Erling Smørgrav 1809a3aaf3SDag-Erling Smørgrav #include "config.h" 1909a3aaf3SDag-Erling Smørgrav #include <sys/types.h> 2009a3aaf3SDag-Erling Smørgrav #include <errno.h> 21*05ab2901SDag-Erling Smørgrav #ifdef HAVE_STDINT_H 2209a3aaf3SDag-Erling Smørgrav #include <stdint.h> 23*05ab2901SDag-Erling Smørgrav #endif 24*05ab2901SDag-Erling Smørgrav #include <limits.h> 2509a3aaf3SDag-Erling Smørgrav #include <stdlib.h> 2609a3aaf3SDag-Erling Smørgrav 2709a3aaf3SDag-Erling Smørgrav /* 2809a3aaf3SDag-Erling Smørgrav * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX 2909a3aaf3SDag-Erling Smørgrav * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW 3009a3aaf3SDag-Erling Smørgrav */ 3109a3aaf3SDag-Erling Smørgrav #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) 3209a3aaf3SDag-Erling Smørgrav 3309a3aaf3SDag-Erling Smørgrav void * 3409a3aaf3SDag-Erling Smørgrav reallocarray(void *optr, size_t nmemb, size_t size) 3509a3aaf3SDag-Erling Smørgrav { 3609a3aaf3SDag-Erling Smørgrav if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 3709a3aaf3SDag-Erling Smørgrav nmemb > 0 && SIZE_MAX / nmemb < size) { 3809a3aaf3SDag-Erling Smørgrav errno = ENOMEM; 3909a3aaf3SDag-Erling Smørgrav return NULL; 4009a3aaf3SDag-Erling Smørgrav } 4109a3aaf3SDag-Erling Smørgrav return realloc(optr, size * nmemb); 4209a3aaf3SDag-Erling Smørgrav } 43