Implement C23 memalignment
Florian Weimer
fweimer@redhat.com
Thu Oct 2 11:39:39 GMT 2025
* Wilco Dijkstra:
> Hi Paul,
>
>> I suggest adding the following paragraph, somewhat derived from Gnulib's
>> documentation for memalignment:
>>
>> Although this function is needed for some theoretical platforms,
>> it is unnecessary on all known practical platforms.
>> To check whether a pointer @var{P} has alignment @var{A},
>> testing @code{(uintptr_t) @var{P} % @var{A}}
>> suffices, and is typically more efficient than
>> comparing @code{memalignment (@var{P})} to @var{A}.
>
> The function definition is unnecessary just like all the abs() variants, sqrt(),
> counting zeroes and so on (basically anything that is just a few instructions
> and can trivially be inlined in compilers).
>
> However we actually do want users to use higher level abstractions. And
> % is a case many people still get wrong - as written above, it will actually
> use a very slow division! We should never give advice that slows code
> down - it's the opposite, calling the function is faster than a division...
The compiler will turn it into a masking operation because the divisor
is a power of two. However, I agree that memalignment is better than
writing out the cast explicitly. C programmers should avoid unnecessary
casts because incorrect casts hide so many errors.
Thanks,
Florian
More information about the Libc-alpha
mailing list