BUG: realloc(p,0) should be consistent with malloc(0)
Vincent Lefevre
vincent@vinc17.net
Wed Jun 18 23:18:07 GMT 2025
On 2025-06-18 22:11:01 +0000, Wilco Dijkstra wrote:
> Hi Alejandro,
>
> > > And those are the 4 words that allow one to call free(p) AND return NULL.
> >
> > By 'one' you mean realloc(p,0), I guess.
> >
> > No. Anything that starts by "If size is non-zero" does NOT give any
> > allowance for what can happen if size is zero.
>
> Of course it does. It HAS to explicitly exclude zero here to allow that case,
> otherwise the zero case must do the same as for any other size, and then
> there would be no point in specifying all the errno crazyness.
It has to explicitly exclude zero, but what is under
"If size is non-zero" applies only to the case where the size
is non-zero; so does not give any spec for the case where the
size is zero. This is what Alejandro meant, I suppose.
> Look at what it claims:
>
> "The ISO C standard makes it implementation-defined whether a call
> to realloc(p, 0) frees the space pointed to by p if it returns a
> null pointer because memory for the new object was not allocated.
> POSIX.1 instead requires that implementations set errno if a null
> pointer is returned and the space has not been freed, and POSIX
> applications should only free the space if errno was changed."
In ISO C99 and C11: "If memory for the new object cannot be allocated,
the old object is not deallocated and its value is unchanged."
So the case "a call to realloc(p, 0) frees the space pointed to by p
if it returns a null pointer because memory for the new object was not
allocated" was not possible with the historical behavior. And currently
(C23), realloc(non-null, 0) is UB.
--
Vincent Lefèvre <vincent@vinc17.net> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / Pascaline project (LIP, ENS-Lyon)
More information about the Libc-alpha
mailing list