BUG: realloc(p,0) should be consistent with malloc(0)
Wilco Dijkstra
Wilco.Dijkstra@arm.com
Tue Jun 17 01:58:41 GMT 2025
Hi Alejandro,
> Any portable application cannot use malloc(0), so why would it want to
> realloc(p,0)?
The purpose of realloc(p, 0) is to free memory. So it is unrelated to whatever
malloc(0) returns - the requirement is to return NULL if the old block remains
valid or a non-NULL new block.
Realloc (p, 0) could return the smallest non-NULL block, which might be malloc(1)
on systems that return NULL for malloc(0). A simple allocator could search for
the smallest available free block, or return the original block if there isn't any
or if the search takes too long.
> After my change, it would become implementation-defined. If you know
> your implementation returns non-null from malloc(0) --and all
> implementations I care about behave like that--, then you can also rely
> on realloc(p,0).
It's hard to know your implementation. You may write your own application,
but when you upgrade your system you may get a different malloc.
> That's enough for many programs. The BSDs, glibc, and musl is already
> enough portability for me. If we convince Bionic too, that's basically
> every modern POSIX system I care about.
There is a world outside of POSIX, and lots of people care about that too...
> Of course I want to fix malloc(0) after this. But if it's already hard
> to convince glibc to fix their broken behavior unilaterally to be
> consistent with everyone else, imagine convincing the C Committee that
> several implementations must be changed. That'll be harder, so please
> expect some year or two before I convince them.
Sure I don't expect it to be easy - there are lots of embedded mallocs around,
practically every RTOS has their own.
However if you want to fix realloc first, I strongly suggest to propose a definition
that actually works for all cases without relying on malloc(0) - that would make
it much more convincing and likely to be adopted.
Cheers,
Wilco
More information about the Libc-alpha
mailing list