What's the point of malloc(0)? What's the point of malloc(0)? c c

What's the point of malloc(0)?


According to the specifications, malloc(0) will return either "a null pointer or a unique pointer that can be successfully passed to free()".

This basically lets you allocate nothing, but still pass the "artist" variable to a call to free() without worry. For practical purposes, it's pretty much the same as doing:

artist = NULL;


The C standard (C17 7.22.3/1) 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, malloc(0) could return NULL or a valid pointer that may not be dereferenced. In either case, it's perfectly valid to call free() on it.

I don't really think malloc(0) has much use, except in cases when malloc(n) is called in a loop for example, and n might be zero.

Looking at the code in the link, I believe that the author had two misconceptions:

  • malloc(0) returns a valid pointer always, and
  • free(0) is bad.

So, he made sure that artist and other variables always had some "valid" value in them. The comment says as much: // these must always point at malloc'd data.


malloc(0) behaviour is implementation specific. The library can return NULL or have the regular malloc behaviour, with no memory allocated. Whatever it does, it must be documented somewhere.

Usually, it returns a pointer that is valid and unique but should NOT be dereferenced. Also note that it CAN consume memory even though it did not actually allocate anything.

It is possible to realloc a non null malloc(0) pointer.

Having a malloc(0) verbatim is not much use though. It's mostly used when a dynamic allocation is zero byte and you didn't care to validate it.