Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the garbage collector preserve an array that is referenced only by raw pointers?

Tags:

People also ask

How is data stored How does the garbage collector work when does it get used?

As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.

How does garbage collector know which objects to free C#?

Garbage Collection succeeds in allocating objects efficiently on the heap memory using the generations of garbage collection. Manual freeing of memory is not needed as garbage collection automatically releases the memory space after it is no longer required.

Are smart pointers garbage collected?

Smart pointers are one of the least efficient forms of garbage collection, particularly in the context of multi-threaded applications when reference counts are bumped atomically.

How garbage collector knows that the object is not in use and needs to be removed?

When the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots.


I'd like to allocate an array of elements from the garbage collected heap, and access those elements only through raw pointers. Is the garbage collector capable of reclaiming that block of memory after (and not before) all the pointers that used to point to it have gone out of scope?

I was thinking 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?