[musl] Bug in reallocf(3) when calling realloc(3)

Alejandro Colomar alx at kernel.org
Sat Jun 21 19:37:06 UTC 2025


Hi Rich,

On Sat, Jun 21, 2025 at 03:27:51PM -0400, Rich Felker wrote:
> 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).

Thanks!

BTW, my message didn't reach freebsd-bugs@, as I'm not subscribed.  If
anyone is subscribed to that list and can resend my message, or can CC a
FreeBSD mainainer, it would be good.


Have a lovely day!
Alex

-- 
<https://www.alejandro-colomar.es/>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://lists.freedesktop.org/archives/libbsd/attachments/20250621/b8454779/attachment.sig>


More information about the libbsd mailing list