DIP 1025--Dynamic Arrays Only Shrink, Never Grow--Community Review Round 1

Dennis dkorpel at gmail.com
Mon Nov 11 22:20:41 UTC 2019

On Monday, 11 November 2019 at 21:41:14 UTC, Walter Bright wrote:
> That's right. I had overlooked that.

It looked like you were aware since you mentioned "although that 
will generate more GC garbage if used in a loop" when referring 
to the workaround of `a = a ~ b`.

> Imagine these 3 lines are spread out over a large code base.

With or without this DIP, that would be problematic.

> On Monday, 11 November 2019 at 21:41:14 UTC, Walter Bright 
> wrote:
> Memory safety cannot be achieved without control over who is 
> the owner of memory.
>> I would like to see an example of memory corruption in `@safe` 
>> code that can happen because of slice appending.
>   @trusted void myfree(void* p) { free(p); }
>   free(slice.ptr);

free cannot be @trusted on a raw pointer type.
In that definition, you can (from @safe code) give `myFree` a 
pointer to a local variable, global variable or GC pointer, all 
of which may corrupt memory. (And I'm ignoring the lack of @live 
here. Without @live you can obviously add double free / 
use-after-free to that list.)

The only way to make `free` safe is to encapsulate it in a struct 
or class that ensures the pointer that is being freed was 
allocated with malloc. If you have a custom type, then 
concatenation like ~= will not work unless you implement it, so 
disabling it on the built-in slice type does not do much good.

In fact, you can consider ~= only syntactic sugar for a call to 
You can disable the ~= construct, but everywhere you would use 
that operator you can still do something functionally equivalent 
and change what kind of data (i.e. stack memory, heap memory) the 
slice refers to.

So the current proposal helps discouraging certain code, but it 
does not prevent anything.

More information about the Digitalmars-d mailing list