1258a0ebeSmrg/*	$OpenBSD: reallocarray.c,v 1.2 2014/12/08 03:45:00 bcook Exp $	*/
2258a0ebeSmrg/*
3258a0ebeSmrg * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
4258a0ebeSmrg *
5258a0ebeSmrg * Permission to use, copy, modify, and distribute this software for any
6258a0ebeSmrg * purpose with or without fee is hereby granted, provided that the above
7258a0ebeSmrg * copyright notice and this permission notice appear in all copies.
8258a0ebeSmrg *
9258a0ebeSmrg * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10258a0ebeSmrg * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11258a0ebeSmrg * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12258a0ebeSmrg * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13258a0ebeSmrg * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14258a0ebeSmrg * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15258a0ebeSmrg * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16258a0ebeSmrg */
17258a0ebeSmrg
18258a0ebeSmrg#ifdef HAVE_CONFIG_H
19258a0ebeSmrg#include <config.h>
20258a0ebeSmrg#endif
21258a0ebeSmrg
22258a0ebeSmrg#include <sys/types.h>
23258a0ebeSmrg#include <errno.h>
24258a0ebeSmrg#include <stdint.h>
25258a0ebeSmrg#include <stdlib.h>
26258a0ebeSmrg#include "reallocarray.h"
27258a0ebeSmrg
28258a0ebeSmrg/*
29258a0ebeSmrg * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
30258a0ebeSmrg * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
31258a0ebeSmrg */
32258a0ebeSmrg#define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
33258a0ebeSmrg
34258a0ebeSmrgvoid *
35258a0ebeSmrgxreallocarray(void *optr, size_t nmemb, size_t size)
36258a0ebeSmrg{
37258a0ebeSmrg	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
38258a0ebeSmrg	    nmemb > 0 && SIZE_MAX / nmemb < size) {
39258a0ebeSmrg		errno = ENOMEM;
40258a0ebeSmrg		return NULL;
41258a0ebeSmrg	}
42258a0ebeSmrg	return realloc(optr, size * nmemb);
43258a0ebeSmrg}
44