1285031Sdes/*	$OpenBSD: reallocarray.c,v 1.2 2014/12/08 03:45:00 bcook Exp $	*/
2285031Sdes/*
3285031Sdes * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
4285031Sdes *
5285031Sdes * Permission to use, copy, modify, and distribute this software for any
6285031Sdes * purpose with or without fee is hereby granted, provided that the above
7285031Sdes * copyright notice and this permission notice appear in all copies.
8285031Sdes *
9285031Sdes * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10285031Sdes * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11285031Sdes * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12285031Sdes * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13285031Sdes * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14285031Sdes * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15285031Sdes * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16285031Sdes */
17285031Sdes
18285031Sdes/* OPENBSD ORIGINAL: lib/libc/stdlib/reallocarray.c */
19285031Sdes
20285031Sdes#include "includes.h"
21285031Sdes#ifndef HAVE_REALLOCARRAY
22285031Sdes
23285031Sdes#include <sys/types.h>
24285031Sdes#include <errno.h>
25285031Sdes#ifdef HAVE_STDINT_H
26285031Sdes#include <stdint.h>
27285031Sdes#endif
28285031Sdes#include <stdlib.h>
29285031Sdes
30285031Sdes/*
31285031Sdes * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
32285031Sdes * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
33285031Sdes */
34285031Sdes#define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
35285031Sdes
36285031Sdesvoid *
37285031Sdesreallocarray(void *optr, size_t nmemb, size_t size)
38285031Sdes{
39285031Sdes	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
40285031Sdes	    nmemb > 0 && SIZE_MAX / nmemb < size) {
41285031Sdes		errno = ENOMEM;
42285031Sdes		return NULL;
43285031Sdes	}
44285031Sdes	return realloc(optr, size * nmemb);
45285031Sdes}
46285031Sdes#endif /* HAVE_REALLOCARRAY */
47