Blame


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