The definition of malloc_usable_size()

H. Peter Anvin hpa@zytor.com
Mon May 4 18:57:20 GMT 2026


On 2026-05-04 11:18, Florian Weimer wrote:
> * H. Peter Anvin:
> 
>> So the definition of malloc_usable_size() states:
>>
>> CAVEATS
>>        The value returned by malloc_usable_size() may be greater than the re‐
>>        quested size of the allocation because of various internal implementa‐
>>        tion details, none of which the programmer should rely on.  This func‐
>>        tion is intended to only be used for diagnostics and statistics; writ‐
>>        ing  to  the  excess memory without first calling realloc(3) to resize
>>        the allocation is not supported.  The returned value is only valid  at
>>        the time of the call.
> 
>> Has *any* version of glibc actually behaved this way (meaning returned
>> a value larger than what would actually be safe to use?)
> 
> That's not the only issue.
> 
> In some cases, it might be convenient for us to merge the immediately
> following allocation into one on which malloc_usable_size has been
> called before.  At this point, the value reported by malloc_usable_size
> changes.  If the application uses malloc_usable_size as a replacement
> for an explicit array length, it may access uninitialized memory in the
> newly appeared tail of the allocation.
> 

So is that a problem (if it is documented that the tail is uninitialized, like
realloc()?)

>
> So even if we never decrease the size of the allocation (which is not
> really possible with our current data structures anyway), it's still not
> safe to treat malloc_usable_size as a fixed value.  The quote from the
> manual page covers this aspect, too.
> 

But it is very different to allow usable memory to spontaneously *increase*.
The amount that was reported as safe to use is still safe to use.

	-hpa



More information about the Libc-alpha mailing list