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

via Digitalmars-d digitalmars-d at puremagic.com
Fri May 15 09:44:39 PDT 2015


On Friday, 15 May 2015 at 16:43:35 UTC, Marc Schütz wrote:
> 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.

Ha! Two fools, one thought :-)


More information about the Digitalmars-d mailing list