Then someone came along and said “NULL should only be returned on
failure”, and decided that their malloc would instead return unique
non-NULL pointers.
seems silly for malloc(0), which looks like it “shouldn’t cost” anything (but does, if that practice is used).
Also, why would someone use malloc(0) instead of malloc(1) for this? Does it really bring significant savings?
Error checking is complicated if malloc(0) returns null. Every check now has to be if (ptr == null && size != 0) or your program will report errors/quit unexpectedly. Or you can add if (size != 0) in front of every malloc call, which is probably even uglier.
I think it’s hard to avoid 0 allocations in all cases. That’s the initial state for many algorithms. Code is a lot cleaner when you don’t have to write everything twice.
Right or wrong, I tend to assume malloc(0) returns a unique pointer (most implementations do, by rounding up). It makes all the rest of the code consistent.
My copy doesn’t say that.
I might be missing something, but this:
seems silly for
malloc(0), which looks like it “shouldn’t cost” anything (but does, if that practice is used).Also, why would someone use
malloc(0)instead ofmalloc(1)for this? Does it really bring significant savings?Error checking is complicated if malloc(0) returns null. Every check now has to be if (ptr == null && size != 0) or your program will report errors/quit unexpectedly. Or you can add if (size != 0) in front of every malloc call, which is probably even uglier.
I think it’s hard to avoid 0 allocations in all cases. That’s the initial state for many algorithms. Code is a lot cleaner when you don’t have to write everything twice.
Right or wrong, I tend to assume malloc(0) returns a unique pointer (most implementations do, by rounding up). It makes all the rest of the code consistent.
Thanks. That makes a lot of sense. I realized, after I wrote that, that a
NULLreturn is a sign of a typically very bad error condition (e.g. OOM).