1 578f13e4 2021-04-25 op /* $OpenBSD: reallocarray.c,v 1.3 2015/09/13 08:31:47 guenther Exp $ */
3 578f13e4 2021-04-25 op * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
5 578f13e4 2021-04-25 op * Permission to use, copy, modify, and distribute this software for any
6 578f13e4 2021-04-25 op * purpose with or without fee is hereby granted, provided that the above
7 578f13e4 2021-04-25 op * copyright notice and this permission notice appear in all copies.
9 578f13e4 2021-04-25 op * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 578f13e4 2021-04-25 op * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 578f13e4 2021-04-25 op * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 578f13e4 2021-04-25 op * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 578f13e4 2021-04-25 op * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 578f13e4 2021-04-25 op * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 578f13e4 2021-04-25 op * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 578f13e4 2021-04-25 op #include "../config.h"
20 578f13e4 2021-04-25 op #include <sys/types.h>
21 578f13e4 2021-04-25 op #include <errno.h>
22 578f13e4 2021-04-25 op #include <stdint.h>
23 578f13e4 2021-04-25 op #include <stdlib.h>
26 578f13e4 2021-04-25 op * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
27 578f13e4 2021-04-25 op * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
29 578f13e4 2021-04-25 op #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
32 578f13e4 2021-04-25 op reallocarray(void *optr, size_t nmemb, size_t size)
34 578f13e4 2021-04-25 op if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
35 578f13e4 2021-04-25 op nmemb > 0 && SIZE_MAX / nmemb < size) {
36 578f13e4 2021-04-25 op errno = ENOMEM;
39 578f13e4 2021-04-25 op return realloc(optr, size * nmemb);