reallocarray.c revision 9dedec0c
19dedec0cSmrg/*	$OpenBSD: reallocarray.c,v 1.2 2014/12/08 03:45:00 bcook Exp $	*/
29dedec0cSmrg/*
39dedec0cSmrg * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
49dedec0cSmrg *
59dedec0cSmrg * Permission to use, copy, modify, and distribute this software for any
69dedec0cSmrg * purpose with or without fee is hereby granted, provided that the above
79dedec0cSmrg * copyright notice and this permission notice appear in all copies.
89dedec0cSmrg *
99dedec0cSmrg * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
109dedec0cSmrg * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
119dedec0cSmrg * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
129dedec0cSmrg * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
139dedec0cSmrg * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
149dedec0cSmrg * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
159dedec0cSmrg * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
169dedec0cSmrg */
179dedec0cSmrg
189dedec0cSmrg#ifdef HAVE_CONFIG_H
199dedec0cSmrg#include <config.h>
209dedec0cSmrg#endif
219dedec0cSmrg
229dedec0cSmrg#include <sys/types.h>
239dedec0cSmrg#include <errno.h>
249dedec0cSmrg#include <stdint.h>
259dedec0cSmrg#include <stdlib.h>
269dedec0cSmrg#include "Xmuint.h"
279dedec0cSmrg
289dedec0cSmrg/*
299dedec0cSmrg * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
309dedec0cSmrg * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
319dedec0cSmrg */
329dedec0cSmrg#define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
339dedec0cSmrg
349dedec0cSmrgvoid *
359dedec0cSmrgXmureallocarray(void *optr, size_t nmemb, size_t size)
369dedec0cSmrg{
379dedec0cSmrg	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
389dedec0cSmrg	    nmemb > 0 && SIZE_MAX / nmemb < size) {
399dedec0cSmrg		errno = ENOMEM;
409dedec0cSmrg		return NULL;
419dedec0cSmrg	}
429dedec0cSmrg	return realloc(optr, size * nmemb);
439dedec0cSmrg}
44