Implement C23 memalignment
Paul Eggert
eggert@cs.ucla.edu
Thu Oct 2 16:59:14 GMT 2025
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.
----
To check whether a pointer @var{P} has alignment @var{A},
testing @code{(uintptr_t) @var{P} & (@var{A} - 1)}
suffices on all but theoretical platforms,
and such a test is typically more efficient than
comparing @code{memalignment (@var{P})} to @var{A}.
To avoid errors due to overuse of casts,
the test can be worded as @code{ptr2uint (@var{P}) & (@var{A} - 1)}
where @code{ptr2uint} is a trivial inlined function
whose body contains the cast to @code{uintptr_t}.
More information about the Libc-alpha
mailing list