Debug help - Programming in D - extending tail slice terminates sharing unexpectedly. Page 69, 70
Serg Gini
kornburn at yandex.ru
Mon Oct 20 10:38:23 UTC 2025
On Monday, 20 October 2025 at 09:50:35 UTC, Brother Bill wrote:
> So all that guidance of tail appending using 'length' and
> 'capacity' is obsolete.
> That is, if the capacity > length, then one can safely extend
> the tail by (capacity - length) elements.
> The new advice is to just not append to slices either for the
> base array or any tail slice array. Otherwise, breakage or
> termination of slice sharing may result.
>
> Do I have that correct?
I've played a bit with code:
```d
import std.stdio;
void main()
{
int[] slice = [1, 3, 5, 7, 9, 11, 13, 15];
int[] tailSlice = slice[$ / 2 .. $];
writeln("slice: ", slice, " length: ", slice.length, "
capacity: ", slice.capacity, "address: ", slice.ptr);
writeln("tailSlice: ", tailSlice, " length: ",
tailSlice.length, " capacity: ", tailSlice.capacity, " address:
", tailSlice.ptr);
writeln("---");
slice[6] = 99;
tailSlice[1] = 55;
writeln("slice: ", slice, " length: ", slice.length, "
capacity: ", slice.capacity, "address: ", slice.ptr);
writeln("tailSlice: ", tailSlice, " length: ",
tailSlice.length, " capacity: ", tailSlice.capacity, " address:
", tailSlice.ptr);
writeln("---");
slice ~= 100;
writeln("slice: ", slice, " length: ", slice.length, "
capacity: ", slice.capacity, "address: ", slice.ptr);
writeln("tailSlice: ", tailSlice, " length: ",
tailSlice.length, " capacity: ", tailSlice.capacity, " address:
", tailSlice.ptr);
writeln("---");
slice[7] = 66;
tailSlice[0] = 44;
slice ~= 111;
writeln("slice: ", slice, " length: ", slice.length, "
capacity: ", slice.capacity, "address: ", slice.ptr);
writeln("tailSlice: ", tailSlice, " length: ",
tailSlice.length, " capacity: ", tailSlice.capacity, " address:
", tailSlice.ptr);
}
```
```
slice: [1, 3, 5, 7, 9, 11, 13, 15] length: 8 capacity: 11address:
7FAE68344000
tailSlice: [9, 11, 13, 15] length: 4 capacity: 7 address:
7FAE68344010
---
slice: [1, 3, 5, 7, 9, 55, 99, 15] length: 8 capacity: 11address:
7FAE68344000
tailSlice: [9, 55, 99, 15] length: 4 capacity: 7 address:
7FAE68344010
---
slice: [1, 3, 5, 7, 9, 55, 99, 15, 100] length: 9 capacity:
11address: 7FAE68344000
tailSlice: [9, 55, 99, 15] length: 4 capacity: 0 address:
7FAE68344010
---
slice: [1, 3, 5, 7, 44, 55, 99, 66, 100, 111] length: 10
capacity: 11address: 7FAE68344000
tailSlice: [44, 55, 99, 66] length: 4 capacity: 0 address:
7FAE68344010
```
But I'm not sure about slice capacity. it doesn't make any sense
for me when it is non-zero
https://dlang.org/spec/arrays.html#capacity-reserve
More information about the Digitalmars-d-learn
mailing list