[musl] Re: realloci(): A realloc() variant that works in-place
Thiago Macieira
thiago@macieira.org
Fri Oct 31 21:06:10 GMT 2025
On Friday, 31 October 2025 13:13:42 Pacific Daylight Time Alejandro Colomar
wrote:
> Consider that realloci() would be significantly cheaper than realloc(3),
> so even if you have an extra function, it might be worth it if it
> succeeds a non-negligible number of times.
>
> From what Thiago says, it seems that it would be worth it for them.
> I suspect it's because things like std::string often grow or shrink by
> small amounts compared to the previous size, as operations on strings
> don't change their length significantly quite often.
Note I'm not talking about growing/shrinking std::strings themselves, but
growing/shrinking arrays (std::vector) of std::strings. The libsdc++
std::string is 32 bytes in size and is not relocatable via memcpy()able.
> So, while it would be one more call in user code, that call is very
> cheap, and the code is really simple to use too:
>
> if (realloci(p, size) == -1)
> fall_back_to_expensive_path();
That's what my example on Godbolt did too.
> I wouldn't categorize it as hard to explain:
>
> int realloci(void *p, size_t size);
>
> realloci() changes the size of the memory block pointed to by
> 'p' to 'size' bytes. This is done in-place, that is, without
> changing its address.
>
> The contents of the memory will be unchanged in the range from
> the start of the region up to the minimum of the old and new
> sizes. If the new size is larger than the old size, the added
> memory will not be initialized.
I'd add: if the new size is smaller than the old size, the bytes in that
storage are undefined, even if this function returned -1. That will allow an
implementation to MADV_DONTNEED the space, even if it can't officially change
the size of the allocation.
Would it be worth returning instead the new size, which may be bigger than the
requested size?
--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
Principal Engineer - Intel Data Center - Platform & Sys. Eng.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 870 bytes
Desc: This is a digitally signed message part.
URL: <https://sourceware.org/pipermail/libc-alpha/attachments/20251031/6b84a30b/attachment.sig>
More information about the Libc-alpha
mailing list