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
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
malloc usually signifies some sort of error has occurred; calling
malloc with a zero size is not actually an error.
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.
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.
When talking about operations with C strings, particularly
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
First and most important of all regarding C strings is this: there is no such thing as C strings.
OK, now that that’s out of the way we can move on. The way to work with strings in C is to treat them as simple sequences of characters, a.k.a. a string in C is stored as an array of char’s. To know where the string ends, it must be terminated by a special marker, which is the ASCII character with the code 0 (commonly known as ‘