On 7/22/20 12:13 AM, Florian Weimer wrote:
I don't think it will work. Try to get an allocation of 4096 bytes with 4096 bytes alignment using glibc malloc this way.
That's just a mental exercise since glibc malloc already has aligned_alloc, but I took the challenge anyway and found that it's eminently doable with glibc malloc alone. Run the attached program, and it should exit with status 0. At least, it works for me.
There is of course some runtime overhead, but the performance should be good enough for many, perhaps even most, Gnulib purposes; and I expect we can tweak it to run faster on Microsoft platforms (which seem to be the only major platform that still don't support aligned allocation natively) if this is a significant concern.
#include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> int main (void) { void *p; for (ptrdiff_t i = 4096; (intptr_t) (p = malloc (i)) & 4095; i++) printf ("allocation of %td bytes yielded unaligned pointer %p\n", i, p); if (!p) printf ("allocation failed\n"); return 0; }