reallocarray.c revision 294407
1165670Sache/*	$OpenBSD: reallocarray.c,v 1.2 2014/12/08 03:45:00 bcook Exp $	*/
2165670Sache/*
3165670Sache * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
4165670Sache *
5165670Sache * Permission to use, copy, modify, and distribute this software for any
6165670Sache * purpose with or without fee is hereby granted, provided that the above
7165670Sache * copyright notice and this permission notice appear in all copies.
8165670Sache *
9165670Sache * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10165670Sache * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11165670Sache * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12165670Sache * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13165670Sache * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14165670Sache * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15165670Sache * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16165670Sache */
17165670Sache
18165670Sache/* OPENBSD ORIGINAL: lib/libc/stdlib/reallocarray.c */
19165670Sache
20165670Sache#include "includes.h"
21165670Sache#ifndef HAVE_REALLOCARRAY
22165670Sache
23165670Sache#include <sys/types.h>
24165670Sache#include <errno.h>
25165670Sache#ifdef HAVE_STDINT_H
26165670Sache#include <stdint.h>
27165670Sache#endif
28165670Sache#include <stdlib.h>
29165670Sache
30165670Sache/*
31165670Sache * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
32165670Sache * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
33165670Sache */
34165670Sache#define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
35165670Sache
36165670Sachevoid *
37165670Sachereallocarray(void *optr, size_t nmemb, size_t size)
38165670Sache{
39165670Sache	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
40165670Sache	    nmemb > 0 && SIZE_MAX / nmemb < size) {
41165670Sache		errno = ENOMEM;
42165670Sache		return NULL;
43165670Sache	}
44165670Sache	return realloc(optr, size * nmemb);
45165670Sache}
46165670Sache#endif /* HAVE_REALLOCARRAY */
47165670Sache