Return value of malloc(0)

Lowell Gilbert lgusenet at be-well.ilk.org
Wed Jun 28 20:19:37 UTC 2006


Andre Albsmeier <Andre.Albsmeier at siemens.com> writes:

>
> The manpage makes me think that when malloc is called with 0
> as argument (and no V-flag had been set) the pointer it returns
> can actually be used (as a pointer to the so-called "minimal
> allocation"). It seems, that firefox "thinks" the same way :-).
> However, it is calculated in malloc.c as a constant and is
> always 0x800 (on my architecture). Any access to this area
> results in a SIGSEV.

The C standard explicitly allows both behaviours, and requires the
implementation to choose one of them.  If it returns a non-NULL
pointer, though, that pointer can *only* be used for passing back to
free().  It may *not* be dereferenced.  So firefox is wrong, and
actually broken.

> I assume the behaviour is meant to show up programming errors:
>
> "If you use malloc(0) and are crazy enough to access the 'allocated'
> memory we give you a SIGSEV to show you how dumb you are :-)".

Yes.  

> In this case the manpage is wrong (or, at least, mis-leading) and
> should be fixed (I could give it a try if someone actually is willing
> to commit it).

I don't see what you are claiming is wrong.  Can you give a brief
description of you're suggesting.

> Apart from that, I suggest, we should run firefox (and maybe other
> mozilla apps) with MALLOC_OPTIONS=V.

That would be reasonable, particularly for the time being.  However,
the firefox bug really should be fixed in the upstream sources.
Writing past the end of an allocated buffer (which is what the code
does, if you think about it) is a serious error.

> Another position could be that firefox is wrong because it NEVER
> may use ANY return value of a malloc(0), regardless of its content.

The C language standard agrees with this position...


More information about the freebsd-hackers mailing list