Setting array length without initializing/reallocating.

rikki cattermole rikki at cattermole.co.nz
Sun Dec 13 20:51:30 UTC 2020


On 14/12/2020 9:03 AM, Jackson22 wrote:
> On Sunday, 13 December 2020 at 17:26:45 UTC, rikki cattermole wrote:
>> On 14/12/2020 6:01 AM, Jackson22 wrote:
>>>>>
>>>>> `array = array.ptr[0..newLength];`
>>>>
>>>> You're setting yourself up for failure with that. What are you 
>>>> trying to "work around"? The allocation, or the initialization?
>>>
>>> How is avoiding an expensive potentially memory leaking operation 
>>> "setting yourself up for failure"?
>>
>> No bounds checking. That slice can extend into memory that isn't of 
>> that type or even allocated to the process.
> 
> No *automatic* bounds checking != no bounds checking.
> 
> There's a reason .ptr exist, I wish people would stop pretending that 
> using it where it is appropriate is somehow going to lead to failure 

I have used it in the past where appropriate with 0 issues resulting 
from it. I do not believe that this is the case here.

> when there are more successful programming languages that have zero 
> automatic bounds checking.

int[] a = [1, 2, 3];
assert(a.ptr is a.ptr[0 .. 4].ptr);

Out of bounds, runs successfully. Doesn't mean that the GC is aware that 
it now has a length of 4.

int[] b = a;
b.length = 4;
assert(a.ptr !is b.ptr);

This is a case where .length is clearly doing the right thing.

int[] c = a;
c.length = 1;
assert(a.ptr is c.ptr);

>> By avoiding that "expensive" memory operation, you instead create a 
>> silent memory corruption in its place which is far worse.
> 
> Why did you quote expensive? Are you implying it isn't expensive? Are 
> you saying re-allocating 4 GB of memory every 6 ms isn't expensive?

Allocating memory is always more expensive than using a buffer where 
life times are known and predictable. You are right about that.

In this case, that isn't what is being described. If length is 
allocating, then that code was not designed to be used with a buffer.

The most expensive thing in this scenario is not allocating memory, it 
is silent memory corruption. Once corrupted not only can the process die 
at any point, but you can't trust its output any longer.


More information about the Digitalmars-d mailing list