Memory allocation purity

Manu via Digitalmars-d digitalmars-d at puremagic.com
Thu May 15 09:01:35 PDT 2014


On 15 May 2014 23:47, Steven Schveighoffer via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
> On Thu, 15 May 2014 09:40:03 -0400, Manu via Digitalmars-d
> <digitalmars-d at puremagic.com> wrote:
>
>> On 15 May 2014 22:30, Steven Schveighoffer via Digitalmars-d
>>
>> <digitalmars-d at puremagic.com> wrote:
>>>
>>> On Thu, 15 May 2014 07:52:20 -0400, Manu via Digitalmars-d
>>> <digitalmars-d at puremagic.com> wrote:
>>>
>>>> On 15 May 2014 10:50, Walter Bright via Digitalmars-d
>>>> <digitalmars-d at puremagic.com> wrote:
>>>>>
>>>>>
>>>>> On 5/14/2014 5:03 PM, Meta wrote:
>>>>>>
>>>>>>
>>>>>>
>>>>>> Allocating memory through new and malloc should always be pure, I
>>>>>> think,
>>>>>> because
>>>>>> failure either returns null in malloc's case,
>>>>>
>>>>>
>>>>>
>>>>>
>>>>> malloc cannot be pure if, with the same arguments, it returns null
>>>>> sometimes
>>>>> and not other times.
>>>>
>>>>
>>>>
>>>> Even if it doesn't fail, malloc called with identical arguments still
>>>> returns a different result every time.
>>>> You can't factor malloc outside a loop and cache the result because
>>>> it's being called repeatedly with the same argument like you're
>>>> supposed to be able to do with any other pure function.
>>>> You shouldn't be able to do that with gcalloc either... how can gcalloc
>>>> be
>>>> pure?
>>>
>>>
>>>
>>> That only applies to strong-pure functions. malloc would be weak-pure,
>>> since
>>> it returns a mutable pointer.
>>
>>
>> Why should returning a mutable pointer imply weak purity?
>
>
> Because if it were strong-pure, the compiler could optimize two sequential
> calls as returning the same exact thing. Imagine if a constructor to a
> mutable object always returned the same object because the constructor's
> parameters were immutable. It would be useless.
>
> -Steve

I don't follow. Forget that it's a pointer... it's just a number. A
strong pure function simply doesn't modify it's inputs (which we can
guarantee with const/immutable args), and returns the same output.
It shouldn't matter if the output is mutable or not, it just has to be
the same. Whether it's the number 10, or a pointer.

I guess it logically follows that the output must be const or
immutable, because it can only possibly be returning a pointer to, or
to a member of, one of it's args... and 'turtles all the way down'.
But that leads me back to where I started... how can it possibly be
that an allocator of any sort can be pure? If you can allocate a new
pointer, you can return it as a const or immutable pointer if you
like, and then the function looks awfully like a strong pure function
even though it returns a new pointer every time. That's not pure at
all.


More information about the Digitalmars-d mailing list