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?
Andrei
There is a third option: return a non-null yet invalid pointer
(e.g. 0x1) that is used exclusively for empty allocations.
This allows the if(p) pattern and elides the cost of allocating
one byte, however it complicates allocator code a bit (resizing,
freeing needs to know about this magic pointer), and breaks the
contract malloc(size)!=malloc(size).