std.allocator.allocate(0) -> return null or std.allocator.allocate(1)?

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Fri May 15 09:36:35 PDT 2015


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


More information about the Digitalmars-d mailing list