Blame lib/reallocarray.c

Packit f00812
/*	$OpenBSD: reallocarray.c,v 1.2 2014/12/08 03:45:00 bcook Exp $	*/
Packit f00812
/*
Packit f00812
 * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
Packit f00812
 *
Packit f00812
 * Permission to use, copy, modify, and distribute this software for any
Packit f00812
 * purpose with or without fee is hereby granted, provided that the above
Packit f00812
 * copyright notice and this permission notice appear in all copies.
Packit f00812
 *
Packit f00812
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
Packit f00812
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
Packit f00812
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
Packit f00812
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
Packit f00812
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
Packit f00812
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
Packit f00812
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Packit f00812
 */
Packit f00812
Packit f00812
/* OPENBSD ORIGINAL: lib/libc/stdlib/reallocarray.c */
Packit f00812
Packit f00812
#include <config.h>
Packit f00812
#ifndef HAVE_REALLOCARRAY
Packit f00812
#undef reallocarray
Packit f00812
Packit f00812
#include <sys/types.h>
Packit f00812
#include <errno.h>
Packit f00812
#ifdef HAVE_STDINT_H
Packit f00812
#include <stdint.h>
Packit f00812
#endif
Packit f00812
#include <stdlib.h>
Packit f00812
Packit f00812
void *reallocarray(void *, size_t, size_t);
Packit f00812
Packit f00812
/*
Packit f00812
 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
Packit f00812
 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
Packit f00812
 */
Packit f00812
#define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
Packit f00812
Packit f00812
void *
Packit f00812
reallocarray(void *optr, size_t nmemb, size_t size)
Packit f00812
{
Packit f00812
	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
Packit f00812
	    nmemb > 0 && SIZE_MAX / nmemb < size) {
Packit f00812
		errno = ENOMEM;
Packit f00812
		return NULL;
Packit f00812
	}
Packit f00812
	return realloc(optr, size * nmemb);
Packit f00812
}
Packit f00812
#endif /* HAVE_REALLOCARRAY */