Implement C23 memalignment
Paul Eggert
eggert@cs.ucla.edu
Thu Oct 2 16:10:30 GMT 2025
On 2025-10-02 04:39, Florian Weimer wrote:
> memalignment is better than
> writing out the cast explicitly. C programmers should avoid unnecessary
> casts because incorrect casts hide so many errors.
I agree that casts are error-prone. However, here the performance of
memalignment is bad enough that some documentation would be helpful. (In
Gnulib we never use memalignment, due to this performance hit.)
Perhaps something like the following instead:
----
To check whether a pointer @var{P} has alignment @var{A},
testing @code{(uintptr_t) @var{P} % @var{A}}
suffices on all but theoretical platforms,
and because the @code{%} is typically implemented via a simple bitmask
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}}
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