[PATCH v2] Implement C23 memalignment

Florian Weimer fweimer@redhat.com
Fri Oct 10 08:25:33 GMT 2025


* Joseph Myers:

> Add the C23 memalignment function (query the alignment of a pointer)
> to glibc.
>
> Given how simple this operation is, it would make sense for compilers
> to inline calls to this function, but I'm treating that as a compiler
> matter (compilers should add it as a built-in function) rather than
> adding an inline version to glibc headers (although such an inline
> version would be reasonable as well).  I've filed
> https://gcc.gnu.org/bugzilla/show_bug.cgi?id=122117 for this feature
> in GCC.

Should this function be added to libc_nonshared.a until the standard is
released, in case its definition changes in subsequent drafts?

> +You can determine the alignment of a pointer with the
> +@code{memalignment} function.
> +
> +@deftypefun size_t memalignment (void *@var{p})
> +@standards{C23, stdlib.h}
> +@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
> +
> +This function, defined in C23, returns the alignment of @var{p}, as a
> +power of two.  If @var{p} is a null pointer, it returns zero.  C23
> +requires @var{p} to be a valid pointer to an object or a null pointer;
> +as a GNU extension, @theglibc{} supports this function on arbitrary
> +bit patterns of pointer type.
> +
> +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}.
> +@end deftypefun

I don't think this performance advice is helpful.  If we want to talk
about performance, we should say something like this instead:

“
In general, performance does not improve if different code is used for
aligned and unaligned pointers.  For example, if you want to read an
@code{int} at the pointer @code{p}, use this code:

@smallexample
int i;
memcpy (&i, p, sizeof (i));
@end smallexample

And then use the value in the variable @code{i}.  The compiler will
generate the most effecient way to access unaligned data for the
architecture, optimizing away the @code{memcpy} call.
”

Thanks,
Florian



More information about the Libc-alpha mailing list