diff options
author | Rich Felker <dalias@aerifal.cx> | 2011-02-20 16:16:33 -0500 |
---|---|---|
committer | Rich Felker <dalias@aerifal.cx> | 2011-02-20 16:16:33 -0500 |
commit | 26031da0f83a2a3ed52190077931ee6c18dfd689 (patch) | |
tree | f1cefeef545766d941e9f0fe1377e9db46ce8aad | |
parent | 598a0147cde14d093d17b81c102a1757b5ef9975 (diff) | |
download | musl-26031da0f83a2a3ed52190077931ee6c18dfd689.tar.gz musl-26031da0f83a2a3ed52190077931ee6c18dfd689.tar.xz musl-26031da0f83a2a3ed52190077931ee6c18dfd689.zip |
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.
-rw-r--r-- | src/malloc/__simple_malloc.c | 2 | ||||
-rw-r--r-- | src/malloc/malloc.c | 14 |
2 files changed, 10 insertions, 6 deletions
diff --git a/src/malloc/__simple_malloc.c b/src/malloc/__simple_malloc.c index c029342c..c8293908 100644 --- a/src/malloc/__simple_malloc.c +++ b/src/malloc/__simple_malloc.c @@ -15,7 +15,7 @@ void *__simple_malloc(size_t n) static int lock; size_t align=1; - if (!n) return 0; + if (!n) n++; if (n > SIZE_MAX/2) goto toobig; while (align<n && align<ALIGN) diff --git a/src/malloc/malloc.c b/src/malloc/malloc.c index d9a30fe4..3c08c41e 100644 --- a/src/malloc/malloc.c +++ b/src/malloc/malloc.c @@ -216,9 +216,14 @@ static int init_malloc() static int adjust_size(size_t *n) { /* Result of pointer difference must fit in ptrdiff_t. */ - if (*n > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) { - errno = ENOMEM; - return -1; + if (*n-1 > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) { + if (*n) { + errno = ENOMEM; + return -1; + } else { + *n = SIZE_ALIGN; + return 0; + } } *n = (*n + OVERHEAD + SIZE_ALIGN - 1) & SIZE_MASK; return 0; @@ -325,7 +330,7 @@ void *malloc(size_t n) struct chunk *c; int i, j; - if (!n || adjust_size(&n) < 0) return 0; + if (adjust_size(&n) < 0) return 0; if (n > MMAP_THRESHOLD) { size_t len = n + PAGE_SIZE - 1 & -PAGE_SIZE; @@ -377,7 +382,6 @@ void *realloc(void *p, size_t n) void *new; if (!p) return malloc(n); - else if (!n) return free(p), (void *)0; if (adjust_size(&n) < 0) return 0; |