malloc(0)

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 NULL from malloc usually signifies some sort of error has occurred; calling malloc with a zero size is not actually an error.
  • returning NULL in 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.

Leave a Reply

Your email address will not be published. Required fields are marked *