Return value of malloc(0)

Bernd Walter ticso at cicely12.cicely.de
Fri Jun 30 16:18:50 UTC 2006


On Fri, Jun 30, 2006 at 06:59:37AM +0200, Johannes Weiner wrote:
> Hi,
> 
> On Thu, Jun 29, 2006 at 07:29:16PM +0200, Matthias Andree wrote:
> > 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?
> 
> > There is no way to see a 0x800 return from malloc(0) as "error".
> 
> So noone should actually use malloc(0) and check the size_t argument before
> passing it, I guess.

But noone should dereference something beyound malloc'ed size.
The following code is broken no matter if x is 0 or anything else,
you always end up accessing data beyond allocated range:
foo = malloc(x);
foo[x] = bar;
It might be Ok not to check x when calling malloc, but is always
required to check if you access something outside the malloc'ed range
unless you can trust your size - in which case you wouldn't had
malloc'ed zero bytes anyway.

-- 
B.Walter                http://www.bwct.de      http://www.fizon.de
bernd at bwct.de           info at bwct.de            support at fizon.de


More information about the freebsd-hackers mailing list