I just saw this code:
artist = (char *) malloc(0);
...and I was wondering why would one do this?
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, andfree(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
.