tech-userlevel archive

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

Re: aligned_alloc c11 function



On Sun, 25 Oct 2015 06:33:39 +0700
Robert Elz <kre%munnari.OZ.AU@localhost> wrote:

> 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.
Thats a nice solution to the problem, thanks for pointing it out.
I will add it.


> 
> 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.
The comment was added for readability, if "Check alignment is a power 
of two and size is a multiple of alignment" is enough I change to that.

> 
> 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.
If you mean the function interface it's out of my control,
bring it up with WG14.

Thanks,
Niclas



Home | Main Index | Thread Index | Old Index