Blob


1 /* $OpenBSD: recallocarray.c,v 1.2 2021/03/18 11:16:58 claudio Exp $ */
2 /*
3 * Copyright (c) 2008, 2017 Otto Moerbeek <otto@drijf.net>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
18 #include "../config.h"
20 #include <errno.h>
21 #include <stdlib.h>
22 #include <stdint.h>
23 #include <string.h>
24 #include <unistd.h>
26 /*
27 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
28 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
29 */
30 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
32 /*
33 * Even though specified in POSIX, the PAGESIZE and PAGE_SIZE
34 * macros have very poor portability. Since we only use this
35 * to avoid free() overhead for small shrinking, simply pick
36 * an arbitrary number.
37 */
38 #define getpagesize() (1UL << 12)
40 void *
41 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
42 {
43 size_t oldsize, newsize;
44 void *newptr;
46 if (ptr == NULL)
47 return calloc(newnmemb, size);
49 if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
50 newnmemb > 0 && SIZE_MAX / newnmemb < size) {
51 errno = ENOMEM;
52 return NULL;
53 }
54 newsize = newnmemb * size;
56 if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
57 oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {
58 errno = EINVAL;
59 return NULL;
60 }
61 oldsize = oldnmemb * size;
63 /*
64 * Don't bother too much if we're shrinking just a bit,
65 * we do not shrink for series of small steps, oh well.
66 */
67 if (newsize <= oldsize) {
68 size_t d = oldsize - newsize;
70 if (d < oldsize / 2 && d < (size_t)getpagesize()) {
71 memset((char *)ptr + newsize, 0, d);
72 return ptr;
73 }
74 }
76 newptr = malloc(newsize);
77 if (newptr == NULL)
78 return NULL;
80 if (newsize > oldsize) {
81 memcpy(newptr, ptr, oldsize);
82 memset((char *)newptr + oldsize, 0, newsize - oldsize);
83 } else
84 memcpy(newptr, ptr, newsize);
86 explicit_bzero(ptr, oldsize);
87 free(ptr);
89 return newptr;
90 }