Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Date: Tue, 15 Jan 2013 13:33:07 +0100
From: Igmar Palsenberg <>
Subject: Re: malloc(0) behaviour

>> 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

That's there to access if size is 0 ? Sure, you can access :

struct foo {

which is size 0. I do wonder what that gives me in practice. That is, not counting the fact that :

if (size == 0)
	size = 1;

was a common practice in malloc() implementations a while ago.

> 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"

He does have a point. If I go to the gas station, hang in the fuel dispencer, pull it out again directly afterwards, and telling the guy behind the desk
that I didn't actually got fuel, I'm probably stared at :)

My way of thinking is just different, and both are fine.
>> 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)

Agree. I always handle that case. 

>> 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

No, just in user code. Libraries shouldn't abort, I agree. In my case, it only aborts in debug mode to aid testing.


Powered by blists - more mailing lists

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