[PATCH] malloc: Improve memalign alignment handling

Paul Eggert eggert@cs.ucla.edu
Tue Feb 24 18:18:50 GMT 2026


On 2026-02-24 09:41, Wilco Dijkstra wrote:

> I've added a testcase to ensure it gets tested, and that found
> bugs in the mcheck checker. So who checks the checkers, and which
> checker checks the checker???

That's a question I often ask in my software engineering classes. :-)

>> 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.

>> This assumes sizeof (void *) is a power of 2, which is a reasonable
>> assumption but that should be stated by adding this:
>>
>>      static_assert (powerof2 (sizeof (void *)));
> 
> We could add tests for this as static asserts, but it's a fundamental assumption
> in malloc (mentioned at the start) and true for all existing targets. The existing
> implementation could never align odd sized pointers.

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.

As a trivia note, as I understand it sizeof (void *) == 6 on the Unisys 
ClearPath Forward Libra 8691 introduced a couple of years ago. This 
platform is descended from the Burroughs B5000 mainframe (1961) and 
retains many of the B5000's quirks. It obviously is not a glibc porting 
target! But the static_assert would check that.


More information about the Libc-alpha mailing list