[PATCH] malloc: Improve memalign alignment handling
Paul Eggert
eggert@cs.ucla.edu
Mon Feb 23 22:31:26 GMT 2026
On 2026-02-23 05:35, Wilco Dijkstra wrote:
> - + __builtin_clz (MAX_TCACHE_SMALL_SIZE)
> - - __builtin_clz (nb);
> + + stdc_count_zeros ((size_t) MAX_TCACHE_SMALL_SIZE)
> + - stdc_count_zeros (nb);
Surely you meant stdc_leading_zeros not stdc_count_zeros, as the latter
is a population count. Similarly elsewhere in the patch.
Given that the patch passed regression tests, that argues the code isn't
being tested enough....
Less important: why is that (size_t) cast needed? MAX_TCACHE_SMALL_SIZE
is already of type size_t, no?
+ alignment = (size_t) 2 << (stdc_count_zeros ((size_t) 1)
+ - stdc_count_zeros (alignment));
Simpler and clearer (and more correct) is the following, which works
because ALIGNMENT is nonzero and is not a power of 2:
alignment = (size_t) 2 << (stdc_bit_width (alignment) - 1);
> - if (alignment % sizeof (void *) != 0
> - || !powerof2 (alignment / sizeof (void *))
> - || alignment == 0)
> + if (alignment < sizeof (void *) || !powerof2 (alignment))
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 *)));
More information about the Libc-alpha
mailing list