Openwall GNU/*/Linux - a small security-enhanced Linux distro for servers
[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Date: Tue, 15 Jan 2013 12:06:18 +0100
From: Szabolcs Nagy <nsz@...t70.net>
To: musl@...ts.openwall.com
Subject: Re: malloc(0) behaviour

* Igmar Palsenberg <igmar@...senberg.com> [2013-01-15 09:31:24 +0100]:
> > fundamental reasons too. Basically they all come down to interactions
> > between the requirements of malloc and realloc, and the fact that
> > returning a null pointer from realloc means failure (and thus that the
> > 
> > http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm
> > http://austingroupbugs.net/view.php?id=400
> > http://sourceware.org/bugzilla/show_bug.cgi?id=12547
> 
> While the above is clear to me, returning a pointer that can't hold anything just seems wrong to me.

i don't think we have too many options here,
the standards and historical practices has
various inconsistencies and musl has the least
broken one

but we can do a theoretical discussion about
the merits of malloc(0)!=0:

i'm surprised that it "seems wrong" to you,
you can access the amount of bytes you requested
through the returned pointer p, evaluating
p+size is valid, p is suitably aligned for all
objects and it can be freed.
these assumptions are broken if malloc(0)==0

if the standard made malloc(0) work in ansi c
then it would save some branch logic and would
made the world a safer place
(because in a fair amount of code that gets
array length from external source no special
casing would be needed for length==0)

in rob pike's words "zero is a perfectly fine value"
http://code.google.com/p/go/issues/detail?id=4142#c2

> It's also a matter of promoting bad code : Doing a malloc(0) is simply a bug. People are just to lazy to check return values,
> and this makes the loop 3 lines shorter.

malloc(0) is implementation-defined with
two different conforming implementations

but either one you choose in practice a lot
of code will rely on the choosen behaviour
incorrectly

returning 0 does not save you from that

returning 0 has the drawback that realloc(0,0)
will be inconsistent
(either with the realloc(0,n)===malloc(n) assumption
or the realloc(p,0) failure reporting when p needs
to be freed)

> I'll wrap malloc() to include an abort in my case :)

but don't do that in library code that may be
used in a long running process: allocation failures
should be reported to let the caller handle it

Powered by blists - more mailing lists

Your e-mail address:

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.