public inbox for glibc-bugs@sourceware.org
help / color / mirror / Atom feed
* [Bug malloc/31222] New: RFE: malloc_size() and/or a realloc() which returns the allocated size
@ 2024-01-08  6:13 hpa at zytor dot com
  0 siblings, 0 replies; only message in thread
From: hpa at zytor dot com @ 2024-01-08  6:13 UTC (permalink / raw)
  To: glibc-bugs

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.

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2024-01-08  6:13 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2024-01-08  6:13 [Bug malloc/31222] New: RFE: malloc_size() and/or a realloc() which returns the allocated size hpa at zytor dot com

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).