Partial arrays reclaimed?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 29 11:47:02 PST 2017


On Friday, January 27, 2017 18:22:17 Nick Sabalausky via Digitalmars-d-learn 
wrote:
> Suppose an array is being used like a FIFO:
>
> -----------------------
> T[] slice;
>
> // Add:
> slice ~= T();
>
> // Remove:
> slice = slice[1..$];
> -----------------------
>
> Assuming of course there's no other references to the memory, as this
> gets used, does the any of the memory from the removed elements ever get
> GC'd?
>
> Also, if this is a long-running process, isn't there a potential danger
> in the array just marching through the address space and running out of
> room? (ie either running out of of continuous space, or hitting 0xFFF....)

Given that a dynamic array refers to a block of memory, whether that's the
whole block of memory or just a portion of it, and that as you shrink the
array, it's just moving where the pointer refers to in the block, there's no
way that it can release the memory. A reallocation would have to take place
so that the elements would be copied to a new block of memory and the
dynamic array would then refer to the new block. And the only times that a
reallocation is going to take place are when you append to the array or when
you call reserve, and the array doesn't have enough capacity to grow in
place to fulfill that reserve.

So, if all you're doing is shrinking the array, then there's no way that any
of its memory is going to be freed. You'd pretty much have to dup it at some
point and assign the new array back to it if you want to make that possible.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list