[PATCH v3] Implement C23 memalignment

Sam James sam@gentoo.org
Thu Oct 16 07:32:37 GMT 2025


Joseph Myers <josmyers@redhat.com> writes:

> 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.
>
> Tested for x86_64 and x86.
>
> ---
>
> Changes in v2: make documentation discuss use on arbitrary bit
> patterns (requested by Florian); discuss direct alignment testing on
> pointers (text from Paul Eggert).
>
> Changes in v3: replace text about alignment testing with Florian's
> proposed wording advising alignment-independent code using memcpy to
> access possibly-unaligned data.
>
> diff --git a/NEWS b/NEWS
> index 8a5c197d42..244f7613d8 100644
> --- a/NEWS
> +++ b/NEWS
> @@ -11,6 +11,8 @@ Major new features:
>  
>  * The ISO C23 memset_explicit function has been added.
>  
> +* The ISO C23 memalignment function has been added.
> +
>  Deprecated and removed features, and other changes affecting compatibility:
>  
>  * Support for dumped heaps has been removed - malloc_set_state() now always
> diff --git a/manual/memory.texi b/manual/memory.texi
> index 6a70168e61..aae180cb6e 100644
> --- a/manual/memory.texi
> +++ b/manual/memory.texi
> @@ -1135,6 +1135,33 @@ The @code{valloc} function is obsolete and @code{aligned_alloc} or
>  @code{posix_memalign} should be used instead.
>  @end deftypefun
>  
> +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.
> +
> +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

efficient

> +architecture, optimizing away the @code{memcpy} call.
> +@end deftypefun

I think the text looks reasonable otherwise.

> [...]

sam


More information about the Libc-alpha mailing list