Memory allocation in D (noob question)
Sean Kelly
sean at f4.ca
Wed Dec 5 08:46:17 PST 2007
Regan Heath wrote:
> Sean Kelly wrote:
>> Regan Heath wrote:
>>> Steven Schveighoffer wrote:
>>>> The problem is that invariant data is changing. This is a no-no for
>>>> pure
>>>> functions which Walter has planned. If invariant data can change
>>>> without violating the rules of the spec, then the compiler
>>>> implementation or design is flawed. I think the design is what is
>>>> flawed.
>>>
>>> That is another issue which I didn't even address.
>>>
>>> Assuming 'string' means 'invariant(char)' and assuming that means the
>>> char values cannot change (I say assuming because I haven't had the
>>> chance to really internalise the new const yet) then I reckon the
>>> implementation of invariant is simply broken/buggy.
>>
>> I don't know that it's broken so much as potentially misleading. That
>> example never actually changed any of the data in the string, it
>> simply appended additional data to the string. Thus invariance of the
>> data was preserved.
>
> [example pasted again for clarity]
>
> > string ab = "ab".idup;
> > string a = ab[0..1];
> > a ~= "c";
> > writefln("ab = ",ab); // also outputs "ac"
>
> True for 'a' but when appending to 'a' it writes over the memory which
> 'ab' guarantees is invariant.
Oops, you're right.
> So, in the general case any slice of invariant data which is shorter
> than the original invariant data can be used to overwrite the original
> invariant data after the slice.
>
> Perhaps ~= should be disabled for invariant arrays.
Or perhaps it should always reallocate. I'd originally thought it
actually did this based on something Walter said, but I misunderstood.
Sean
More information about the Digitalmars-d
mailing list