[Bug 1730] Change malloc(0) behavior to match FreeBSD and Linux

bugzilla-daemon at rtems.org bugzilla-daemon at rtems.org
Fri Jan 28 04:21:57 UTC 2011


https://www.rtems.org/bugzilla/show_bug.cgi?id=1730

--- Comment #11 from Ralf Corsepius <ralf.corsepius at rtems.org> 2011-01-27 22:21:55 CST ---
(In reply to comment #10)
> (In reply to comment #5)
> > (In reply to comment #4)
> > b) your sentence above is wrong.

> Too lazy do dig out my old UltraSparc but I'm pretty sure Solaris also returns
> non NULL
I can add what a SunOS4 manpage tells:

> malloc(), realloc(), memalign() and valloc() return a non-NULL pointer
> if size is 0, and calloc() returns a non-NULL pointer if nelem or elsize
> is 0, but these pointers should not be deref‐
>       erenced.

... I stay corrected.

> To follow the law of least surprise RTEMS should also return  a valid pointer,
> and to be real traditional Unix alike it should return a unique pointer each
> time it is called.
I do not agree to this. I consider malloc(0) returning non-NULL to be a
disadvantage:

* A malloc(0) returning NULL normally will lead to hard-segfaults once such
pointer is dereferenced. Dereferencing a malloc(0) returned non-NULL pointer
will lead to silent memory-leaks.
 I prefer hard core-dumps over silently misbehaving applications.

* (ptr = malloc(size)) && ptr != NULL is a common idom to check for "out of
memory. If malloc(0) returns 0 this automatically catches "size = 0".
=> This leads to safer run-time behavior.


In other words: 
* I consider malloc(0) returning NULL to be superior.
* As this is allowed per POSIX, I don't see any reasons for changing this.

@Sebastian: What is the actual issue you are trying to resolve - Which use case
of malloc(0) you tripped over is trouble-some because malloc(0) returns 0?

> BTW: this is one useful way to use malloc(0) pointers: to get a unique pointer
> value.   This usage isn't totally portable of course but  quite portable.
Jikes ... there are many hacks and exploits of the C language to shoot yourself
into the foot ;)

-- 
Configure bugmail: https://www.rtems.org/bugzilla/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
You are watching all bug changes.



More information about the bugs mailing list