Can memset() be called with a null pointer if the size is 0?

Kerrek SB picture Kerrek SB · Dec 21, 2011 · Viewed 10k times · Source

For one reason or another, I want to hand-roll a zeroing version of malloc(). To minimize algorithmic complexity, I want to write:

void * my_calloc(size_t size)
{
    return memset(malloc(size), 0, size);
}

Is this well-defined when size == 0? It is fine to call malloc() with a zero size, but that allows it to return a null pointer. Will the subsequent invocation of memset be OK, or is this undefined behaviour and I need to add a conditional if (size)?

I would very much want to avoid redundant conditional checks!

Assume for the moment that malloc() doesn't fail. In reality there'll be a hand-rolled version of malloc() there, too, which will terminate on failure.

Something like this:

void * my_malloc(size_t size)
{
    void * const p = malloc(size);
    if (p || 0 == size) return p;
    terminate();
}

Answer

Pubby picture Pubby · Dec 21, 2011

Here is the glibc declaration:

extern void *memset (void *__s, int __c, size_t __n) __THROW __nonnull ((1));

The __nonnull shows that it expects the pointer to be non-null.