move alignment check from aligned_alloc to posix_memalign
[musl] / src / malloc / aligned_alloc.c
1 #include <stdlib.h>
2 #include <stdint.h>
3 #include <errno.h>
4
5 /* This function should work with most dlmalloc-like chunk bookkeeping
6  * systems, but it's only guaranteed to work with the native implementation
7  * used in this library. */
8
9 void *aligned_alloc(size_t align, size_t len)
10 {
11         unsigned char *mem, *new, *end;
12         size_t header, footer;
13
14         if ((align & -align) != align) {
15                 errno = EINVAL;
16                 return NULL;
17         }
18
19         if (len > SIZE_MAX - align) {
20                 errno = ENOMEM;
21                 return NULL;
22         }
23
24         if (align <= 4*sizeof(size_t)) {
25                 if (!(mem = malloc(len)))
26                         return NULL;
27                 return mem;
28         }
29
30         if (!(mem = malloc(len + align-1)))
31                 return NULL;
32
33         header = ((size_t *)mem)[-1];
34         new = (void *)((uintptr_t)mem + align-1 & -align);
35
36         if (!(header & 7)) {
37                 ((size_t *)new)[-2] = ((size_t *)mem)[-2] + (new-mem);
38                 ((size_t *)new)[-1] = ((size_t *)mem)[-1] - (new-mem);
39                 return new;
40         }
41
42         end = mem + (header & -8);
43         footer = ((size_t *)end)[-2];
44
45         ((size_t *)mem)[-1] = header&7 | new-mem;
46         ((size_t *)new)[-2] = footer&7 | new-mem;
47         ((size_t *)new)[-1] = header&7 | end-new;
48         ((size_t *)end)[-2] = footer&7 | end-new;
49
50         if (new != mem) free(mem);
51         return new;
52 }