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

bugzilla-daemon at rtems.org bugzilla-daemon at rtems.org
Fri Jan 28 16:56:43 UTC 2011


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

Gedare <giddyup44 at yahoo.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |giddyup44 at yahoo.com

--- Comment #12 from Gedare <giddyup44 at yahoo.com> 2011-01-28 10:56:42 CST ---
(In reply to comment #11)
> (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.
> 
This depends on the architecture/linker. Some allow mapping address 0.

> * (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.
> 
Agreed.

> 
> 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.
> 
I understand the reason to stay consistent with other POSIX OSs, but it seems
like code that relies on this behavior will fail. If the only advantage is that
free gets a valid pointer, I don't see malloc(0) returning NULL as a problem.

I second the request for a use case / issue.

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