Blame


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