Return value of malloc(0)

Harti Brandt hartmut.brandt at dlr.de
Thu Jun 29 17:45:49 UTC 2006


On Thu, 29 Jun 2006, Matthias Andree wrote:

MA>Johannes Weiner <hnazfoo at googlemail.com> writes:
MA>
MA>> On Thu, Jun 29, 2006 at 06:09:37PM +0200, Matthias Andree wrote:
MA>>
MA>>> The value returned from malloc(0) must not be dereferenced whatever it
MA>>> was. It was 0x800, which doesn't count as "failure".
MA>>
MA>> But this would be appropriate for catching the error:
MA>>
MA>> if ((foo = malloc(0)) == foo)
MA>> 	/* make noise */
MA>>
MA>> wouldn't it?
MA>
MA>No, sir. Operator precedence: assign first, and then compare, thus the
MA>comparison will always be true (else you'd be comparing to undefined
MA>values, which isn't any better).  You might as well write:

Operator precedence is just for parsing, not for evaluation. The 
compiler may well first evaluate the foo on the right side of the == (by 
fetching it) and then go an call malloc and assign foo.

It is actually undefined behaviour, I think, so it may well make explode 
your near-by atom power plant.

harti

MA>
MA> foo = malloc(0);
MA> /* make noise */
MA>
MA>There is no way to see a 0x800 return from malloc(0) as "error".
MA>
MA>


More information about the freebsd-hackers mailing list