I just saw this code:
artist = (char *) malloc(0);
...and I was wondering why would one do this?
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.
Yes, free(malloc(0)) is guaranteed to work.
malloc is used to allocate memory. You can use a pointer by either allocating it with malloc or making it point to an already allocated portion of memory.
The + 1 is to make room for the NUL terminator. If you want a string of length n , your array has to be of length n + 1 ; n spaces for the n characters of the string, and 1 space for the terminator. By the way, you shouldn't cast the return value of malloc . It will make your code easier to change in the future.
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, 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With