Return value of malloc(0)

Pat Lashley patl+freebsd at volant.org
Thu Jun 29 15:45:20 UTC 2006


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


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 


More information about the freebsd-hackers mailing list