Blame


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