On Friday, 15 May 2015 at 16:36:29 UTC, Andrei Alexandrescu wrote:
This is a matter with some history behind it. In C, malloc(0)
always returns a new, legit pointer that can be subsequently
reallocated, freed etc. What most malloc() implementations
practically do in their first line is:
if (size == 0) size = 1;
and take it from there.
The reasoning was to make failure of malloc easy to test for.
This would suffice:
size_t s;
...
void* p = malloc(s);
if (!p) {
... failed! ...
}
as opposed to:
if (!p && s) {
... failed! ...
}
That kinda makes sense, but it's not super consistent. For
example, realloc() does not obey the same protocol. Calling
realloc() with a new size of 0 actually free()s the pointer and
then returns null.
Anyhow, on to D. In D it's easy to test whether an allocation
succeeded:
auto buf = alloc.allocate(s);
if (buf.length != s) {
... failed! ...
}
It is a bit subtle, but I think overall it makes everyone's
life easier. Thoughts?
Not necessarily a good idea, but there's a third option:
return cast(void*) -1;
Or some other arbitrary non-zero value.