How can I clean array and prevent further reallocation if there's enough space already?

Adam D. Ruppe destructionator at gmail.com
Sun Feb 7 21:55:34 UTC 2021


On Sunday, 7 February 2021 at 21:40:12 UTC, Jack wrote:
> I think it would be fine except it assumes the number of items 
> of the array to doesn't grow, it rather overwritten new elements
>
> from docs:
>
> "Use this only when it is certain there are no elements in use 
> beyond the array in the memory block. If there are, those 
> elements will be overwritten by appending to this array."

That's referring to a case like this:

int[] a = [1, 2, 3, 4, 5];
int[] b = a[0 .. 3];

Normally, if you were to do

b ~= 6;

it would allocate a new array for b, leaving a alone.

a == [1, 2, 3, 4, 5];
b == [1, 2, 3, 6];

a.ptr != b.ptr because b got reallocated.



If you assumeSafeAppended there though, the b ~= 6 would reuse 
the remainder of the block.

b.assumeSafeAppend();
b ~= 6;

a == [1, 2, 3, 6, 5];
b == [1, 2, 3, 6];

a.ptr == b.ptr; // assumeSafeAppend meant no reallocation




So the "elements in use beyond the array in the memory block" are 
referring to the variable a in the example still having [4, 5] at 
the end. Since that 4 gets overwritten by the 6, if you weren't 
prepared for this, it can be a surprising bug.

The docs also say this is "undefined behavior" simply because the 
4 won't *always* get overwritten by the 6. well, in this case the 
4 is always overwritten by the 6, but say I wanted to append [6, 
7, 8], then it might reallocate anyway because the memory block 
is only big enough for two new elements, not three. If that 
happened, that 4 would stay put.

So the array is allowed to grow as much as it wants, just in some 
cases it will overwrite existing data and in other cases it will 
realloc a new slice to make room.


More information about the Digitalmars-d-learn mailing list