Return value of malloc(0)
patl+freebsd at volant.org
Fri Jun 30 16:15:53 UTC 2006
> I went wandering through the C Working Group archives for the heck of
> it, and apparently a lot of people were confused over this, thinking
> either as you did or that "unique" meant it would a value unique to
> the usage of malloc(0). It's been clarified recently (and will be in
> the next revision of the standard) to the meaning you understood.
> If the size of the space requested is zero, the behavior is
> implementation-defined: either a null pointer is returned, or the
> behavior is as if the size were some nonzero value, except that
> the returned pointer shall not be used to access an object.
> > But if it did actually perform a
> > minimum allocation'; wouldn't it have to return a different value
> > every time to maintain the free() semantics?
> I think that's another way of looking at the same confusion. If
> "minimum" is zero, then using a sentinel value (as in FreeBSD) works.
But the standard, as you quoted above, says 'as if the size were some NONZERO
value'; so using a sentinel value is NOT standards-compliant.
> Our malloc() could be easily fixed to be standards-compliant by
> removing the special handling for ZEROSIZEPTR in malloc.c; then
> allocations of 0 bytes will be rounded up to 16, just like all other
> alloations of less than 16 bytes. However, that would lose much of
> the bug-finding advantage of the current behaviour.
But how often does this particular type of bug occur? If often enough, how hard
would it be to make zero-sized allocations come from some special chunk of
address space that is reserved to always generate a fault on access (from user
space)? (And, of course, fix realloc() to recognize pointers in that range and
do the right thing.)
Also, under what circumstances could a zero-sized allocation fail (using our
current scheme)? Is it really useful to maintain the distinction between
'failed' and 'successfully allocated no space'? Would it be better to just take
the simple route of returning NULL for zero-sized allocations?
> This is wandering into -standards territory, though. In any case, the
> answer to thread's original question is "mozilla should fix its code
> to not assume malloc(0)==NULL".
Agreed. (With the usual observation that they, too, are a mainly
volunteer-based project; and would probably appreciate the inclusion of a patch
with the bug report. And, of course, that the original poster of this thread
should file a bug report with the Mozilla project.)
More information about the freebsd-hackers