[PATCH] malloc: Improve memalign alignment handling
Wilco Dijkstra
Wilco.Dijkstra@arm.com
Mon Mar 2 13:36:06 GMT 2026
Hi Paul,
>>> why is that (size_t) cast needed? MAX_TCACHE_SMALL_SIZE
>>> is already of type size_t, no?
>>
>> It is indeed, but how are we sure it doesn't ever change? So the size_t is
>> explicit to show it must be a size_t (unfortunately there is no _sz variant
>> of the stdbit macros).
>
> OK, but why does it need to be a size_t? If it's just (say) 'int', the
> code still works, right? If we omit the cast, I'm not seeing any failure
> mode here that wouldn't be caught be the compiler.
Since it computes a difference in bitwidth using clz, it must do the clz on
the same type. We could switch to bitwidth for that expression too since
it then no longer relies on the size of the types. Let me check if it generates
the same code.
> We could add the static_assert near the comment where this constraint is
> mentioned.
>> Note POSIX requires alignment to be both a power of 2 and a multiple of
>> sizeof (void *), so it also requires that the pointer size must be a power of 2.
>
> But the POSIX wording for posix_memalign doesn't say "and". It says "The
> value of alignment shall be a power of two multiple of sizeof (void *)".
> Hence the alignment could be (say) 48 when sizeof (void *) is 6.
Maybe they changed it recently, but that's impossible to support in general.
You'd have to set the minimum alignment to least common multiple - if you
have 16-byte and 6 byte types that would be like 48, and structure layout
will end up with huge amounts of padding.
Cheers,
Wilco
More information about the Libc-alpha
mailing list