Return value of malloc(0)
Andre.Albsmeier at siemens.com
Sun Jul 2 14:34:37 UTC 2006
On Sat, 01-Jul-2006 at 10:35:47 +0200, Matthias Andree wrote:
> Pat Lashley <patl+freebsd at volant.org> writes:
> > BUT, that said, the safest and most portable coding practice would be:
> > // The C standard does not require malloc(0) to return NULL;
> > // but whatever it returns MUST NOT be dereferenced.
> > ptr = ( size == 0 ) ? NULL : malloc( size ) ;
> Safest (avoiding null derefence) would instead be:
> ptr = malloc(size ? size : 1);
I hacked malloc.c to do exactly this automatically, just for
testing. 15 Minutes after rebooting (and after doing a lot of
desktop switching and opening and closing of windows) the
X-server ran out of memory :-).
I assume there are lots of programs out there which do
malloc(0) but only firefox (and apparently seamonkey)
dereference the returned non-NULL pointer and crash therefore.
More information about the freebsd-hackers