Does the garbage collector keep an array referenced only by the source pointers?

I would like to select an array of elements from the collected garbage heap and access these elements only with raw pointers. Can the garbage collector restore this memory block after (and not earlier) all the pointers that pointed to it are out of scope?

I thought of doing it like this:

{ int* ptrToArray1 = (new int[](100)).ptr; int* ptrToArray2 = ptrToArray1; int* ptrToArray3 = ptrToArray1 + 10; ptrToArray1 += 50; ptrToArray2 += 99; *ptrToArray1 = 123; *ptrToArray2 = 456; *ptrToArray3 = 789; ptrToArray1 -= 42; ptrToArray2 -= 24; //... and so on ... Is the array data guaranteed to be there? } // Now that all the pointers are out of scope, can the // garbage collector reclaim the memory block of that array? 
+8
garbage-collection arrays heap-memory d d2
source share
1 answer

Your script will work.

Two things:

  • The garbage collector is conservative. This means that it scans the raw words of the stack, registers and heap GC. Everything that looks like a pointer to a GC-allocated memory will be considered as such and, therefore, save this part of the memory in real time.
  • The garbage collector allows the use of internal pointers. The reason for this is twofold. Firstly, iteration through raw memory is quite common (in the system language) using only pointer arithmetic, so the GC should handle a situation where only the offset pointer points to the GC's memory. Secondly, the interfaces in D really just shift from the base object, so they need to save the original object in real time.

It is worth noting that internal pointers significantly slow down the phase of marking the garbage collector, but in a system language such as D, not supporting internal pointers would be unreasonable.

Finally, note that if you store a pointer to GC-allocated memory outside the GC heap and stack / registers, it will not be selected by GC. That is, if you store some .ptr array in some malloc 'd-memory, and then delete all references to it, for example, it will not be considered live.

+14
source share

All Articles