Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/coreutils/src/compat/recallocarray.c
1067 views
1
/* $OpenBSD: recallocarray.c,v 1.1 2017/03/06 18:44:21 otto Exp $ */
2
/*
3
* Copyright (c) 2008, 2017 Otto Moerbeek <[email protected]>
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
#include "compat.h"
18
19
#include <errno.h>
20
#include <stdlib.h>
21
#include <stdint.h>
22
#include <string.h>
23
#include <unistd.h>
24
25
/*
26
* This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
27
* if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
28
*/
29
#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
30
31
void *
32
recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
33
{
34
size_t oldsize, newsize;
35
void *newptr;
36
37
if (ptr == NULL)
38
return calloc(newnmemb, size);
39
40
if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
41
newnmemb > 0 && SIZE_MAX / newnmemb < size) {
42
errno = ENOMEM;
43
return NULL;
44
}
45
newsize = newnmemb * size;
46
47
if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
48
oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {
49
errno = EINVAL;
50
return NULL;
51
}
52
oldsize = oldnmemb * size;
53
54
/*
55
* Don't bother too much if we're shrinking just a bit,
56
* we do not shrink for series of small steps, oh well.
57
*/
58
if (newsize <= oldsize) {
59
size_t d = oldsize - newsize;
60
61
if (d < oldsize / 2 && d < getpagesize()) {
62
memset((char *)ptr + newsize, 0, d);
63
return ptr;
64
}
65
}
66
67
newptr = malloc(newsize);
68
if (newptr == NULL)
69
return NULL;
70
71
if (newsize > oldsize) {
72
memcpy(newptr, ptr, oldsize);
73
memset((char *)newptr + oldsize, 0, newsize - oldsize);
74
} else
75
memcpy(newptr, ptr, newsize);
76
77
explicit_bzero(ptr, oldsize);
78
free(ptr);
79
80
return newptr;
81
}
82
83