1 /* $OpenBSD: recallocarray.c,v 1.1 2017/03/06 18:44:21 otto 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 */
17
18 #include <errno.h>
19 #include <stdckdint.h>
20 #include <stdlib.h>
21 #include <stdint.h>
22 #include <string.h>
23 #include <unistd.h>
24
25 void *recallocarray(void *, size_t, size_t, size_t);
26
27 void *
recallocarray(void * ptr,size_t oldnmemb,size_t newnmemb,size_t size)28 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
29 {
30 size_t oldsize, newsize;
31 void *newptr;
32
33 if (ptr == NULL)
34 return calloc(newnmemb, size);
35
36 if (ckd_mul(&newsize, newnmemb, size)) {
37 errno = ENOMEM;
38 return NULL;
39 }
40
41 if (ckd_mul(&oldsize, oldnmemb, size)) {
42 errno = EINVAL;
43 return NULL;
44 }
45
46 /*
47 * Don't bother too much if we're shrinking just a bit,
48 * we do not shrink for series of small steps, oh well.
49 */
50 if (newsize <= oldsize) {
51 size_t d = oldsize - newsize;
52
53 if (d < oldsize / 2 && d < (size_t)getpagesize()) {
54 memset((char *)ptr + newsize, 0, d);
55 return ptr;
56 }
57 }
58
59 newptr = malloc(newsize);
60 if (newptr == NULL)
61 return NULL;
62
63 if (newsize > oldsize) {
64 memcpy(newptr, ptr, oldsize);
65 memset((char *)newptr + oldsize, 0, newsize - oldsize);
66 } else
67 memcpy(newptr, ptr, newsize);
68
69 explicit_bzero(ptr, oldsize);
70 free(ptr);
71
72 return newptr;
73 }
74