[Bug malloc/31222] New: RFE: malloc_size() and/or a realloc() which returns the allocated size

hpa at zytor dot com sourceware-bugzilla@sourceware.org
Mon Jan 8 06:13:37 GMT 2024


https://sourceware.org/bugzilla/show_bug.cgi?id=31222

            Bug ID: 31222
           Summary: RFE: malloc_size() and/or a realloc() which returns
                    the allocated size
           Product: glibc
           Version: unspecified
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P2
         Component: malloc
          Assignee: unassigned at sourceware dot org
          Reporter: hpa at zytor dot com
  Target Milestone: ---

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.

-- 
You are receiving this mail because:
You are on the CC list for the bug.


More information about the Glibc-bugs mailing list