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.

C strings – part II

In the last post, the one talking about C strings, I promised a sequel about common problems when doing seemingly innocent operations with them, so here it is.
The list is by no means complete. It is actually very short, just 3 or 4 points. If you care to add more, feel free.

Overlapping strings

When talking about operations with C strings, particularly strcat and strcpy, I mentioned these should not be used with overlapping strings. In case the reasons were not evident enough, we’ll look at some examples. Keep in mind how these functions work, that is the fact that they rely only on the terminating '' character for determining where a string ends.
Now let’s see a small piece of code: Continue reading C strings – part II