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

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Fri May 15 12:49:27 PDT 2015


On 5/15/15 11:51 AM, Andrei Alexandrescu wrote:
> On 5/15/15 11:37 AM, deadalnix 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.
>>>
>>
>> There are actually 2 way to do this in malloc. Either you return null,
>> but then you need to be able to accept null in the free implementation
>> (as malloc must return a freeable pointer) or you just bump to 1.
>>
>> Both are valid per spec and there are implementations of malloc for both.
>
> Ah, nice. I was under the misconception that malloc(0) cannot return
> null in C. Apparently it's implementation defined at least since C99,
> see http://stackoverflow.com/a/2132318/348571. Thanks!

Well I added the rule that allocate(0) should return null, there are a 
few more tests but probably nothing worrisome: 
https://github.com/andralex/phobos/commit/f73f6ecf1b45b0fc3cffd50d375eb15eb2311220

Andrei




More information about the Digitalmars-d mailing list