Setting array length without initializing/reallocating.
Bastiaan Veelo
Bastiaan at Veelo.net
Sat Dec 12 13:33:47 UTC 2020
On Saturday, 12 December 2020 at 00:53:09 UTC, Jonathan Levi
wrote:
> Wow, there went several hours of debugging.
>
> Increasing the length of a slice, by setting its length, will
> initialize the new elements and reallocate if necessary.
>
> I did not realize length was "smart", I guess I should have
> guessed.
>
> Anyway, to work around this, and probably also be more clear,
> create a new slice from the same pointer.
>
> `array = array.ptr[0..newLength];`
Hold on -- how does this not corrupt memory? As soon as the
length exceeds the allocated capacity (the point at which the
slice would be reallocated when setting its length) you will have
a silent out of bounds violation, identical to overflowing a C
array.
Am I wrong??
If you do not want the expansion to be initialized, I guess you
could allocate a new uninitialized slice and copy contents over
explicitly.
--Bastiaan.
More information about the Digitalmars-d
mailing list