[musl] Bug in reallocf(3) when calling realloc(3)
Rich Felker
dalias at libc.org
Sat Jun 21 19:27:51 UTC 2025
On Sat, Jun 21, 2025 at 09:10:58PM +0200, Alejandro Colomar wrote:
> Bon dia Guillem,
>
> I've just checked the implementation of reallocf(3bsd), and it looks
> like it has a memory leak. Admittedly, a small one, but I just wanted
> to report it. I'll suggest two proposals, plus keeping the status quo,
> and explain the advantages of each of them.
>
> Here's the current code in libbsd:
>
> $ grepc -tfd reallocf .
> ./src/reallocf.c:void *
> reallocf(void *ptr, size_t size)
> {
> void *nptr;
>
> nptr = realloc(ptr, size);
>
> /*
> * When the System V compatibility option (malloc "V" flag) is
> * in effect, realloc(ptr, 0) frees the memory and returns NULL.
> * So, to avoid double free, call free() only when size != 0.
> * realloc(ptr, 0) can't fail when ptr != NULL.
> */
> if (!nptr && ptr && size != 0)
> free(ptr);
> return (nptr);
> }
>
> The last sentence in that comment is false. realloc(nonnull,0) can fail
> in systems in which realloc(nonnull,0) normally returns non-null, such
> as the BSDs or musl. Let's say the system is unable to find enough
> space for the metadata necessary for the new 0-sized block of memory.
> It would return NULL and keep the old pointer intact.
>
> I've CCed musl@ so that they can verify that this is true on their
> implementation. I didn't see anything in their code suggesting that it
> can't fail.
Yes this is true. realloc returning null *always* indicates failure
(and accordingly, memory has not been freed) in our past and current
implementations, and indeed it can fail when resizing down (to zero or
otherwise).
Rich
More information about the libbsd
mailing list