tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: aligned_alloc c11 function



    Date:        Sat, 24 Oct 2015 19:42:45 +0200
    From:        Niclas Rosenvik <nros%NetBSD.org@localhost>
    Message-ID:  <20151024194245.58b090e0%NetBSD.org@localhost>

  | Hi, I have already discussed this with other NetBSD developers 
  | but to make it public I wanted to send a mail to tech-userland.

posix_memalign() requires alignment to be at least sizeof(void *)
which means allocating aligned memory with smaller requirements is not
portable.  (posix_memalign(pp, sizeof(int), n) might work, or might not
-- even long instead of int);

There's nothing that can be done about posix_memalign() but there's
no need to perpetuate the bug.

So, I'd suggest adding

	while (alignment < sizeof (void *))
		alignment <<= 1;

after the validity tests, before the call to posix_memalign().
(You could add a __predict_false() in the test if you wanted).

nb: after the validity tests so size is not required to be a multiple
of sizeof(void *) as well.

That way, the requirements of posix_memalign are met, and this function
would work for any alignment at all (it might end up returning memory
that is "more" aligned than requested, but that's always possible in any
case.)

Naturally the man page would also require an adjustment.

I also don't think you really need to include comments that explain why
(n & m-1) etc is OK.    Just "Check alignment is a power of two and size
is a multiple of alignment" would be sufficient I think.  libc source
code is not the right place to be teaching binary arithmetic ops.

kre

ps: personally, I'd prefer the args in the other order, with the
more important size arg first, but that's just a matter of taste.

pps: everything Christos said too.



Home | Main Index | Thread Index | Old Index