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

Idan Arye via Digitalmars-d digitalmars-d at puremagic.com
Sun May 17 01:35:48 PDT 2015


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

How about defining `alloc.allocate(0)` to *be* an error?


More information about the Digitalmars-d mailing list