1287915Sdes/* $OpenBSD: reallocarray.c,v 1.1 2014/05/08 21:43:49 deraadt Exp $ */ 2287915Sdes/* 3287915Sdes * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> 4287915Sdes * 5287915Sdes * Permission to use, copy, modify, and distribute this software for any 6287915Sdes * purpose with or without fee is hereby granted, provided that the above 7287915Sdes * copyright notice and this permission notice appear in all copies. 8287915Sdes * 9287915Sdes * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10287915Sdes * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11287915Sdes * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12287915Sdes * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13287915Sdes * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14287915Sdes * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15287915Sdes * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16287915Sdes */ 17287915Sdes 18287915Sdes#include "config.h" 19287915Sdes#include <sys/types.h> 20287915Sdes#include <errno.h> 21294190Sdes#ifdef HAVE_STDINT_H 22287915Sdes#include <stdint.h> 23294190Sdes#endif 24294190Sdes#include <limits.h> 25287915Sdes#include <stdlib.h> 26287915Sdes 27287915Sdes/* 28287915Sdes * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX 29287915Sdes * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW 30287915Sdes */ 31287915Sdes#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) 32287915Sdes 33287915Sdesvoid * 34287915Sdesreallocarray(void *optr, size_t nmemb, size_t size) 35287915Sdes{ 36287915Sdes if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 37287915Sdes nmemb > 0 && SIZE_MAX / nmemb < size) { 38287915Sdes errno = ENOMEM; 39287915Sdes return NULL; 40287915Sdes } 41287915Sdes return realloc(optr, size * nmemb); 42287915Sdes} 43