make malloc(0) return unique pointers rather than NULL
this change is made with some reluctance, but i think it's for the best. correct programs must handle either behavior, so there is little advantage to having malloc(0) return NULL. and i managed to actually make the malloc code slightly smaller with this change.
This commit is contained in:
@@ -15,7 +15,7 @@ void *__simple_malloc(size_t n)
|
|||||||
static int lock;
|
static int lock;
|
||||||
size_t align=1;
|
size_t align=1;
|
||||||
|
|
||||||
if (!n) return 0;
|
if (!n) n++;
|
||||||
if (n > SIZE_MAX/2) goto toobig;
|
if (n > SIZE_MAX/2) goto toobig;
|
||||||
|
|
||||||
while (align<n && align<ALIGN)
|
while (align<n && align<ALIGN)
|
||||||
|
|||||||
+9
-5
@@ -216,9 +216,14 @@ static int init_malloc()
|
|||||||
static int adjust_size(size_t *n)
|
static int adjust_size(size_t *n)
|
||||||
{
|
{
|
||||||
/* Result of pointer difference must fit in ptrdiff_t. */
|
/* Result of pointer difference must fit in ptrdiff_t. */
|
||||||
if (*n > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) {
|
if (*n-1 > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) {
|
||||||
errno = ENOMEM;
|
if (*n) {
|
||||||
return -1;
|
errno = ENOMEM;
|
||||||
|
return -1;
|
||||||
|
} else {
|
||||||
|
*n = SIZE_ALIGN;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
*n = (*n + OVERHEAD + SIZE_ALIGN - 1) & SIZE_MASK;
|
*n = (*n + OVERHEAD + SIZE_ALIGN - 1) & SIZE_MASK;
|
||||||
return 0;
|
return 0;
|
||||||
@@ -325,7 +330,7 @@ void *malloc(size_t n)
|
|||||||
struct chunk *c;
|
struct chunk *c;
|
||||||
int i, j;
|
int i, j;
|
||||||
|
|
||||||
if (!n || adjust_size(&n) < 0) return 0;
|
if (adjust_size(&n) < 0) return 0;
|
||||||
|
|
||||||
if (n > MMAP_THRESHOLD) {
|
if (n > MMAP_THRESHOLD) {
|
||||||
size_t len = n + PAGE_SIZE - 1 & -PAGE_SIZE;
|
size_t len = n + PAGE_SIZE - 1 & -PAGE_SIZE;
|
||||||
@@ -377,7 +382,6 @@ void *realloc(void *p, size_t n)
|
|||||||
void *new;
|
void *new;
|
||||||
|
|
||||||
if (!p) return malloc(n);
|
if (!p) return malloc(n);
|
||||||
else if (!n) return free(p), (void *)0;
|
|
||||||
|
|
||||||
if (adjust_size(&n) < 0) return 0;
|
if (adjust_size(&n) < 0) return 0;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user