malloc(0)
can either return a null pointer or a pointer to a 0 length region of memory. We can deal with this variation in one of (at least) 3 ways.
#define xnalloc(_t,_n) ((_t*)malloc((_n)*sizeof(_t)))
#define xnalloc(_t,_n) \
( ((_n)==0) ? ((_t*)0) : ((_t*)malloc((_n)*sizeof(_t))) )
#define xnalloc(_t,_n) \
( assert((_n) != 0 ), ((_t*)malloc((_n)*sizeof(_t))) )
My personal preference is to pick the third. Occasionally it is legitimate to allocate a 0 length object. In that case, we have to write:
if( n == 0 ) {
p = 0;
}
else {
p = xnalloc(Type, n);
}
However, fairly often when we are allocating a 0 length object it indicates the presence of a potential bug (n
should never have been 0), or a performance optimization (if n
is 0, then there is no work to be done, so don't execute the rest of the function).