Blame


1 578f13e4 2021-04-25 op /* $OpenBSD: reallocarray.c,v 1.3 2015/09/13 08:31:47 guenther Exp $ */
2 578f13e4 2021-04-25 op /*
3 578f13e4 2021-04-25 op * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
4 578f13e4 2021-04-25 op *
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.
8 578f13e4 2021-04-25 op *
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.
16 578f13e4 2021-04-25 op */
17 578f13e4 2021-04-25 op
18 578f13e4 2021-04-25 op #include "../config.h"
19 578f13e4 2021-04-25 op
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>
24 578f13e4 2021-04-25 op
25 578f13e4 2021-04-25 op /*
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
28 578f13e4 2021-04-25 op */
29 578f13e4 2021-04-25 op #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
30 578f13e4 2021-04-25 op
31 578f13e4 2021-04-25 op void *
32 578f13e4 2021-04-25 op reallocarray(void *optr, size_t nmemb, size_t size)
33 578f13e4 2021-04-25 op {
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;
37 578f13e4 2021-04-25 op return NULL;
38 578f13e4 2021-04-25 op }
39 578f13e4 2021-04-25 op return realloc(optr, size * nmemb);
40 578f13e4 2021-04-25 op }