Re: [PATCH v2] rust: alloc: satisfy `aligned_alloc` requirements

From: Alejandro Colomar
Date: Sat Feb 08 2025 - 15:31:04 EST


Hi Paul,

On Sat, Feb 08, 2025 at 12:09:40PM -0800, Paul Eggert wrote:
> On 2025-02-08 11:19, Alejandro Colomar wrote:
> > I wonder why glibc silently overaligns aligned_alloc() without reporting
> > an error for an alignment of 2, while it reports an error for an
> > alignment of 3. It doesn't make much sense at first glance.
>
> Why doesn't it make sense?
>
> If the underlying memory management system supports only some power-of-two
> alignments including one alignment greater than 2, it is easy to support
> alignment of 2 by overaligning, but it is not possible to support an
> alignment of 3.

Hmmm, I thought the memory management system could find some
overalignment that would be multiple of 3 and that could work (maybe
3 * page size, as a big hammer). But maybe some implementation details
just don't allow that, so I guess it's fair to reject it. Sounds
reasonable.

Do you happen to know why the memalign(3) description says that the
alignment must be a power of two when it doesn't do any validation and
just rounds up as necessary? I'll send a patch for the manual page, but
it would be good to know if something has changed about it at some
point. Maybe in the past it did have different requirements?


Have a lovely night!
Alex

alx@devuan:~/tmp/gcc$ cat overalign.c
#define _GNU_SOURCE
#include <errno.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>

int
main(void)
{
int i;
void *p;

errno = 0;
p = aligned_alloc(3, 3);
printf("aligned_alloc(3, 3): %p; %#m\n", p);

puts("");
puts("non-power of two, alignof(void*)");

errno = 0;
p = aligned_alloc(24, 24);
printf("aligned_alloc(24, 24): %p; %#m\n", p);

puts("");
puts("Power of two, alignof(void*)");

errno = 0;
p = aligned_alloc(8, 8);
printf("aligned_alloc(8, 8): %p; %#m\n", p);
}
alx@devuan:~/tmp/gcc$ cc overalign.c
alx@devuan:~/tmp/gcc$ ./a.out
aligned_alloc(3, 3): (nil); EINVAL

non-power of two, alignof(void*)
aligned_alloc(24, 24): (nil); EINVAL

Power of two, alignof(void*)
aligned_alloc(8, 8): 0x55ba005056b0; 0

--
<https://www.alejandro-colomar.es/>

Attachment: signature.asc
Description: PGP signature