[PATCH] malloc: Improve checked_request2size
Wilco Dijkstra
Wilco.Dijkstra@arm.com
Wed Jun 11 12:34:08 GMT 2025
Hi DJ,
> Wilco Dijkstra <Wilco.Dijkstra@arm.com> writes:
>> Change checked_request2size to return PTRDIFF_T+1 for huge inputs. This
>> ensures large allocation request stay large and can't be confused with a
>> small allocation.
>
> Every call to checked_request2size() immediately checks for 0 and
> returns NULL if so. I don't see an opportunity for confusion here,
This is currently used in eg. __libc_calloc:
# define usize2tidx(x) csize2tidx (checked_request2size (x))
size_t tc_idx = usize2tidx (bytes);
if (__glibc_likely (tc_idx < mp_.tcache_bins))
... tcache code
Since csize2tidx does (x) - MINSIZE, we get 0 - MINSIZE which is huge,
so a huge input implies a huge index, and all is fine.
However if you change it to do this (from Cupertino's patch):
- size_t tc_idx = usize2tidx (bytes);
- if (__glibc_likely (tc_idx < mp_.tcache_bins))
+ size_t nb = checked_request2size (bytes);
+ if (nb < mp_.tcache_max_bytes)
Now a huge size is changed into nb = 0 and then 0 < mp_.tcache_max_bytes
means we enter the tcache code and treat it like a valid size...
So my patch avoids this confusion by keeping huge sizes always huge.
> comparing with 0 is far more efficient than comparing against a random
> 64-bit constant.
SIZE_MAX does the job too, so I'll do that in v2.
Cheers,
Wilco
More information about the Libc-alpha
mailing list