Does the GC consider slice lengths?

Ali Çehreli acehreli at yahoo.com
Fri Apr 1 16:24:33 UTC 2022


void main() {
   auto a = new int[1_000_000];

   auto b = a[0..1];  // Hold on to the first element

   a = a[$-1..$];     // Drop all but the last element

   // Are the middle elements gone, or is b keeping
   // them alive just because it still holds the very
   // first pointer?

   // Attempt to access original elements through
   // a pointer to the first element. Bug?
   auto c = b.ptr[0..1_000_000];
}

One assumption might be that the GC remembers the single large 
allocation as one and all of the elements are still available? But if it 
considers slices and their lengths specially, then it would see that the 
mid section is not referenced any more.

I would not do that but one wonders... :)

A related question is whether the memory for earlier elements are freed 
as they are popped off from the front. I know by experience that the 
memory for earlier elements are indeed freed. So one can use D's arrays 
as queues without memory issues: Add to the end, pop from the front...

Ali


More information about the Digitalmars-d-learn mailing list