I wrote: > According to our doc, there are three possible behaviours of the realloc > function: > With a non-NULL pointer argument p, C17 says that it is > implementation-defined whether realloc (p, 0) frees p. Behavior varies > on > (A) whether realloc (p, 0) always frees p and successfully returns a > null pointer, or > (B) always fails and leaves p valid, or > (C) usually succeeds and returns a unique zero-size object. > And there is also > (D) usually succeeds and returns a pointer to freshly-allocated memory > of 1 byte. > (I believe we should mention this fourth possibility in > doc/posix-functions/realloc.texi.)
Done as follows: 2024-10-19 Bruno Haible <br...@clisp.org> realloc: Improve documentation. * doc/posix-functions/realloc.texi: Regarding realloc(p,0), document what the platforms actually do, not merely theoretical possibilities. diff --git a/doc/posix-functions/realloc.texi b/doc/posix-functions/realloc.texi index bd130195c2..9eec174fa1 100644 --- a/doc/posix-functions/realloc.texi +++ b/doc/posix-functions/realloc.texi @@ -26,12 +26,30 @@ on whether a unique zero-size object is created. With a non-NULL pointer argument @code{p}, C17 says that it is implementation-defined whether @code{realloc (p, 0)} frees @code{p}. -Behavior varies on whether @code{realloc (p, 0)} always frees @code{p} -and successfully returns a null pointer, or always -fails and leaves @code{p} valid, or usually succeeds and returns a -unique zero-size object; a program not suspecting these variations in -semantics will leak memory (either the still-valid @code{p}, or the -non-NULL return value). +Behavior varies among systems: @code{realloc (p, 0)} +@itemize +@item +always frees @code{p} and successfully returns a null pointer +(on glibc, AIX, native Windows, Android). +@item +usually succeeds and +returns a pointer to freshly-allocated memory of 1 byte +(on musl libc, macOS, FreeBSD, NetBSD, OpenBSD, Solaris, Cygwin). +@item +always fails and leaves @code{p} valid (no known system does this), or +@item +usually succeeds and returns a unique zero-size object +(no known system does this). +@end itemize +A program not suspecting these variations in semantics will +@itemize +@item +either leak memory (the still-valid @code{p}), +if it assumes the first behaviour but the system implements the second one, +@item +have double-free bugs, +if it assumes the second behaviour but the system implements the first one. +@end itemize Extension: Gnulib provides a module @samp{realloc-gnu} that substitutes a @code{realloc} implementation that behaves more like the glibc implementation.