malloc(0)
Posted by ionutl on March 12th, 2010
You’re probably used to always checking the size you’re passing to malloc to make sure it’s greater than zero. But have you wandered what happens if you do malloc(0)?
The C bible (a.k.a. the standard) says something like this in section 7.20.3:
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.
You can try on your preferred compiler and see how it behaves.
I personally adhere to the second variant, returning a non-null pointer to a block of memory of size zero, for reasons like:
- a return value of
NULLfrommallocusually signifies some sort of error has occurred; callingmallocwith a zero size is not actually an error. - returning
NULLin this special case would probably mean a new test done on each and every allocation, even though the cases in which the parameter is actually zero are most likely incredibly rare; so not doing this might be a (small) optimization.
Tags: malloc, Programming
Posted in Programming | No Comments »

