2 * Copyright (c) 2008, 2017 Otto Moerbeek <otto@drijf.net>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 /* OPENBSD ORIGINAL: lib/libc/stdlib/recallocarray.c */
28 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
29 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
31 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
34 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
36 size_t oldsize, newsize;
40 return calloc(newnmemb, size);
42 if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
43 newnmemb > 0 && SIZE_MAX / newnmemb < size) {
47 newsize = newnmemb * size;
49 if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
50 oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {
54 oldsize = oldnmemb * size;
57 * Don't bother too much if we're shrinking just a bit,
58 * we do not shrink for series of small steps, oh well.
60 if (newsize <= oldsize) {
61 size_t d = oldsize - newsize;
63 if (d < oldsize / 2 && d < (size_t)getpagesize()) {
64 memset((char *)ptr + newsize, 0, d);
69 newptr = malloc(newsize);
73 if (newsize > oldsize) {
74 memcpy(newptr, ptr, oldsize);
75 memset((char *)newptr + oldsize, 0, newsize - oldsize);
77 memcpy(newptr, ptr, newsize);
79 explicit_bzero(ptr, oldsize);