GC.malloc is pure - wat

Nordlöw via Digitalmars-d digitalmars-d at puremagic.com
Thu Mar 31 14:25:20 PDT 2016


On Friday, 24 April 2015 at 15:05:15 UTC, anonymous wrote:
> GC.malloc is marked pure. But it isn't, is it?
>
> This should hold for a pure function:
>     assert(f(x) == f(x));
> This fails with GC.malloc, of course.
>
> Or consider this:
>     auto v = f(x);
>     auto w = f(x);
> When f is pure, a compiler should be free to reuse the value of 
> v for w. That's no good with GC.malloc, obviously.

A solution is to fake purity through

extern(C) pure nothrow @system @nogc
{
     void* malloc(size_t size);
     void* realloc(void* ptr, size_t size);
     void free(void* ptr);
}

Pay attention to the use of malloc() though.

Note that this makes malloc() strongly pure (its single 
parameters is passed by value). Therefore successive calls to 
malloc() with the same argument will be optimized away and all 
those calls will return the same values as the first call. When 
used in allocators this shouldn't be a problem, though.

Used successfully at

https://github.com/nordlow/justd/blob/master/packedarray.d#L6


More information about the Digitalmars-d mailing list