[PATCH 2/3] Document malloc alignment
Florian Weimer
fweimer@redhat.com
Fri Feb 6 09:38:37 GMT 2026
* Paul Eggert:
> * manual/memory.texi (Malloc Examples, Changing Block Size)
> (Allocating Cleared Space):
> Document the alignment of the returned value.
> ---
> manual/memory.texi | 26 ++++++++++++++++++++++----
> 1 file changed, 22 insertions(+), 4 deletions(-)
>
> diff --git a/manual/memory.texi b/manual/memory.texi
> index f85e8ef26d..38c279eeff 100644
> --- a/manual/memory.texi
> +++ b/manual/memory.texi
> @@ -652,10 +652,13 @@ savestring (const char *ptr, size_t len)
> @end group
> @end smallexample
>
> -The block that @code{malloc} gives you is guaranteed to be aligned so
> -that it can hold any type of data. On @gnusystems{}, the address is
> -always a multiple of eight on 32-bit systems, and a multiple of 16 on
> -64-bit systems. Only rarely is any higher boundary (such as a page
> +In @theglibc{}, the block that @code{malloc} gives you is guaranteed
> +to be aligned so that its address is a multiple of
> +@code{alignof (max_align_t)}, so that it can hold object types
> +with any fundamental alignment and without stricter alignment specifiers.
> +On @gnusystems{}, this means the address is a multiple of 16 or of 8,
> +depending on the system.
> +Only rarely is any higher boundary (such as a page
> boundary) necessary; for those cases, use @code{aligned_alloc} or
> @code{posix_memalign} (@pxref{Aligned Memory Blocks}).
I think this should cross-reference Replacing malloc, and mention that
malloc replacements sometimes do not follow this rule.
> +@item
> +In implementations other than @theglibc{}, a non-null pointer returned
> +by @code{malloc (@var{size})} is guaranteed to be aligned only for
> +fundamentally-aligned objects of size at most @code{max (@var{size}, 1)}.
I don't understand this.
I think the rule is that sizes of the fundamental alignment and larger
have fundamental alignment, but sizes less than the fundamental
alignment have alignment that is the largest power of two less than the
size. Maybe that's equivalent to your formulation in many cases? I
would like us to avoid to get into a debate here what constitutes a
fundamentally aligned object.
> +Any non-null pointer returned by @code{realloc} satisfies the same
> +alignment restrictions as a similar pointer returned by @code{malloc}
> +with the same size.
Please mention here that any special alignment created by memalign et
al. will be lost after realloc.
> +In @theglibc{}, the vector is aligned the same way that @code{malloc}
> +aligns its returned values. In other implementations, it is merely
> +aligned suitably for any array of fundamentally-aligned elements each
> +with size at most @code{max (@var{size}, 1)}.
Is this a C standard thing? Does the same rule apply to calloc, which
has a similar element count/element size split after all?
Thanks,
Florian
More information about the Libc-alpha
mailing list