Date: Thu, 29 Jun 2006 21:27:18 +0200 From: Erik Trulsson <ertr1013@student.uu.se> To: Pat Lashley <patl+freebsd@volant.org> Cc: Stefan Farfeleder <stefan@fafoe.narf.at>, freebsd-hackers@freebsd.org, Andre Albsmeier <Andre.Albsmeier@siemens.com> Subject: Re: Return value of malloc(0) Message-ID: <20060629192718.GA65675@owl.midgard.homeip.net> In-Reply-To: <805AA34B676EDF411B3CF548@Zelazny> References: <20060628181045.GA54915@curry.mchp.siemens.de> <20060628212956.GI822@wombat.fafoe.narf.at> <805AA34B676EDF411B3CF548@Zelazny>
next in thread | previous in thread | raw e-mail | index | archive | help
On Thu, Jun 29, 2006 at 11:44:23AM -0400, Pat Lashley wrote: > >The C Standard says the following about malloc(0): > > > > If the size of the space requested is zero, the behavior is > > implementation-defined: either a null pointer is returned, or the > > behavior is as if the size were some nonzero value, except that the > > returned pointer shall not be used to access an object. > > > >So our default behaviour to crash if a pointer returned by malloc(0) is > >dereferenced is legal and a good one because it catches errors like the > >above one. > > No, our implementation is NOT legal. We always return the SAME value. To > be legal, we should not return that value again unless it has been > free()-ed. > > first = malloc(0) ; > second = malloc(0) ; > > if ( first == second ) ERROR( "C standards violation" ) ; Almost. The test should be if ( first != NULL && first == second) ERROR( "C standards violation" ) ; It is after all legal for malloc(0) to return NULL. Otherwise you are correct. Having malloc(0) always returning the same (non-NULL) value is not legal according to the C standard. C99 says: 7.20.3 Memory management functions [...] Each such allocation shall yield a pointer to an object disjoint from any other object. [...] If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object. > > > Firefox, or the extension, has a bug in the code. It should not be > attempting to de-reference the result of a 'malloc(0)' call. They probably > depend on having it return NULL, which is checked elsewhere. (The fix is > for them to test for the size == zero case and just set the pointer to NULL > instead of calling malloc(0). But that's their problem, not ours.) > > > > -Pat > _______________________________________________ > freebsd-hackers@freebsd.org mailing list > http://lists.freebsd.org/mailman/listinfo/freebsd-hackers > To unsubscribe, send any mail to "freebsd-hackers-unsubscribe@freebsd.org" -- <Insert your favourite quote here.> Erik Trulsson ertr1013@student.uu.se
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20060629192718.GA65675>