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