BUG: realloc(p,0) should be consistent with malloc(0)

Alejandro Colomar alx@kernel.org
Tue Jun 17 18:42:12 GMT 2025


Hi Wilco,

On Tue, Jun 17, 2025 at 11:52:18AM +0000, Wilco Dijkstra wrote:
> > POSIX.1-2024 has a weird wording.  Quoting POSIX.1-2024:
> 
> | If size is 0,
> ...
> | either:
> |    -  A null pointer shall be returned
> |       and, if ptr is not a null pointer, errno shall be set to EINVAL.
> |    -  A pointer to the allocated space shall be returned,
> |       and the memory object pointed to by ptr shall be freed.
> ...
> 
> > Indeed, glibc seems non-conforming to POSIX.1-2024.  More reason to fix
> > the broken and non-conforming glibc implementation now.
> 
> As far as I can tell, it does still allow the first case to free the memory:
> 
> "If size is non-zero and memory for the new object is not allocated, the old object shall not be deallocated."

Read the first 4 words of that sentence.  "If size is non-zero".  We're
talking about realloc(p,0).  That sentence you've quoted doesn't cover
this scenario.

You're mixing things.

> So my proposal would be to change it to something like:
> 
> "If memory for the new object is not allocated, the old object shall not be deallocated."
> 
> "A null pointer shall be returned if the memory object pointed to by ptr is not freed."

Current POSIX.1-2024 is fine.  glibc is not.

> >> 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.
> >
> > No?  I bet malloc(0) is never going to return NULL on glibc or the BSDs.
> > That would break tons of existing code.
> 
> Whether malloc(0) does or doesn't break code is a different argument from realloc.
> POSIX does allow malloc(0) to return NULL:
> 
> "If the size of the space requested is 0, the behavior is implementation-defined:
> either a null pointer shall be returned, or the behavior shall be as if the size were some non-zero value, ..."

It does.  And such systems are also hard to use for similar reasons.
Luckily, those systems are rare in POSIX land, and are dying.


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://sourceware.org/pipermail/libc-alpha/attachments/20250617/a8102ca2/attachment.sig>


More information about the Libc-alpha mailing list