The C standard (the link is to the N1570 draft) says:
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 if your malloc_or_exit()
function is called with an argument of 0
, it may either terminate your program (if malloc(0)
returns NULL
), or it may return a non-null pointer that may not be dereferenced (dereferencing such a pointer would cause undefined behavior).
If you want to treat a zero-sized allocation as an error, you can modify your wrapper function (untested):
void *malloc_or_exit(size_t size) {
void *result;
if (size == 0) {
exit(EXIT_FAILURE);
}
else if ((result = malloc(size)) == NULL) {
exit(EXIT_FAILURE);
}
else {
return result;
}
}