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. */
9 void *aligned_alloc(size_t align, size_t len)
11 unsigned char *mem, *new, *end;
12 size_t header, footer;
14 if ((align & -align & -sizeof(void *)) != align) {
19 if (len > SIZE_MAX - align) {
24 if (align <= 4*sizeof(size_t)) {
25 if (!(mem = malloc(len)))
30 if (!(mem = malloc(len + align-1)))
33 header = ((size_t *)mem)[-1];
34 end = mem + (header & -8);
35 footer = ((size_t *)end)[-2];
36 new = (void *)((uintptr_t)mem + align-1 & -align);
39 ((size_t *)new)[-2] = ((size_t *)mem)[-2] + (new-mem);
40 ((size_t *)new)[-1] = ((size_t *)mem)[-1] - (new-mem);
44 ((size_t *)mem)[-1] = header&7 | new-mem;
45 ((size_t *)new)[-2] = footer&7 | new-mem;
46 ((size_t *)new)[-1] = header&7 | end-new;
47 ((size_t *)end)[-2] = footer&7 | end-new;
49 if (new != mem) free(mem);