Setting array length without initializing/reallocating.

Mike Parker aldacron at gmail.com
Mon Dec 14 01:28:33 UTC 2020


On Sunday, 13 December 2020 at 20:03:46 UTC, 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"?

"avoiding an expensive potentially memory leaking operation" is 
not the issue, it's how the OP is going about it.

Based on the OP's question and the example, the impression I get 
is that it's an attempt to arbitrarily increase the length of a 
slice with no regard to the capacity of its memory store. If 
`newLength` is greater than the remaining capacity in the memory 
store, then the new length will go beyond whatever has been 
allocated. That is what I meant by "setting yourself up for 
failure", and that is why the lack of bounds checking is an issue 
here. |

Steven's post lays out other potential issues with taking this 
approach in D.

>>
>> 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.
>

But even with manual bounds checking, there has to be enough 
memory allocated somewhere to hold the new array elements. For a 
dynamically resizable array, there is no escaping the need to 
allocate memory. The cost can be mitigated by allocating enough 
up front, or with a tailored reallocation strategy, but it can't 
be eliminated.


More information about the Digitalmars-d mailing list