Return value of malloc(0)
Pat Lashley
patl+freebsd at volant.org
Fri Jun 30 16:31:02 UTC 2006
> > No, sir. Operator precedence: assign first, and then compare, thus the
> > comparison will always be true (else you'd be comparing to undefined
> > values, which isn't any better). You might as well write:
> >
> > foo = malloc(0);
> > /* make noise */
>
> Ok, just for having it done:
>
> if (foo == (foo = some_val))
>
> .. would be right to check if foo stayed the same. No?
No. As far as I know, there is no requirement in the standard that the left
side of an inequality be evaluated before the right side; or that there is any
need for consistency in order of evaluation. (And even if I'm wrong and the C
standard does specify evaluation order, other languages may not; so depending
on it would be a bad habit to form.)
> > There is no way to see a 0x800 return from malloc(0) as "error".
The point is that that value is NOT an error indicator at all. (As discussed
elsewhere, it isn't quite standards-compliant; since we always return the same
value for malloc(0); but the malloc -did- succeed.)
> So noone should actually use malloc(0) and check the size_t argument before
> passing it, I guess.
The error was later when they attempted to de-reference the pointer returned
from the 'malloc(0)'; not in the allocation itself.
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 ) ;
-Pat
More information about the freebsd-hackers
mailing list