Blame


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