Bug 31222 - RFE: malloc_size() and/or a realloc() which returns the allocated size
Summary: RFE: malloc_size() and/or a realloc() which returns the allocated size
Status: UNCONFIRMED
Alias: None
Product: glibc
Classification: Unclassified
Component: malloc (show other bugs)
Version: unspecified
: P2 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2024-01-08 06:13 UTC by H. Peter Anvin
Modified: 2024-01-08 06:13 UTC (History)
0 users

See Also:
Host:
Target:
Build:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description H. Peter Anvin 2024-01-08 06:13:37 UTC
glibc currently provides malloc_usable_size(), which has the caveat:

of which the programmer should rely on. This function is intended to only be used for diagnostics and statistics; writing 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.

In contrast, BSD provides malloc_size(), which provides the permanently allocated size of the memory area, which can be relied upon by the programmer.

This is really useful in a loop of this form:

void *buf = NULL;
size_t bufsiz = 0;

while (1) {
    size_t needbuf = bufsiz;
    function_writing_to_sized_buffer(buf, &needbuf, ....);
    if (needbuf <= bufsiz)
        break; /* Buffer big enough, operation successful */
    buf = realloc(buf, needbuf);  /* Need to handle realloc() failure */
    bufsiz = needbuf;
}

This form is safe against function_writing_to_sized_buffer() not producing the same output on a subsequent call.

However, this also means that work is thrown away unnecessarily if the block actually returned by realloc() was rounded to a value big enough and the realloc() was unnecessary.