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