Implement C23 memalignment
Zack Weinberg
zack@owlfolio.org
Thu Oct 2 17:15:58 GMT 2025
On Thu, Oct 2, 2025, at 12:59 PM, Paul Eggert wrote:
> On 2025-10-02 09:44, Wilco Dijkstra wrote:
>> Writing it as p & (a - 1) would be better since that really does avoid division.
>> However I still don't see why we would need to document anything at all
>
> It's helpful to document it because memalignment is a new primitive
> which has a purpose that is not entirely clear to many programmers, and
> which has dicey performance in what would naively be a common use case.
>
> You're right about the division of course; I was assuming the usual case
> where A is a constant. Here's revised wording that also removes one of
> the "typically"s.
>
> I wish this kind of documementation were not needed, but we're stuck
> with memalignment as standardized, and should document its gotchas.
I don't like the "<alternative> suffices on all but theoretical platforms"
wording at all. It reminds me of all the passive aggressive language about
how C89 allows for weird possibilities that Will Not Happen On The GNU
SystemTM, elsewhere in the manual.
I also don't think the manual should be in the business of lecturing people
about how to do pointer arithmetic correctly, especially not as an aside to
reference documentation for specific functions. (I'd welcome a "how to code
defensively in C" chapter if someone wanted to write it.)
The performance issues can and should be addressed by making this function
into a compiler intrinsic. Meanwhile, I suggest this wording instead:
| On all presently supported systems, when @var{A} is a power of two,
| @code{memalignment (@var{P}) == @var{A}} is equivalent to
| @code{((uintptr_t) @var{P}) & (@var{A - 1})}. If @var{A} is certain
| to be a power of two, it may be more efficient to use this formula
| instead of calling @code{memalignment}, especially with compilers
| that don't recognize @code{memalignment} as a built-in function
| like @code{alignof}.
zw
More information about the Libc-alpha
mailing list