I apologize if the answer to this question is trivial. But I still cannot figure out this by myself.
How does the garbage collector in .NET identify what objects on the heap are garbage and what objects are not?
Lets say a .NET application is running and at a certain point of time garbage collection occurs(lets leave out the generations and finalization queue for simplicity sake).
Now the application may have:
- stack variables pointing to objects on heap.
- registers containing addresses of objects on heap.
- Static variables pointing to objects on heap.
This is how I ASSUME the GC works.
- It de-references each such address and ends up at the object on the heap.
- It marks the object as not garbage (by using the sync block index) since some variable is still pointing to it.
- It does this operation for all the addresses(referred to as roots for some reason in most articles)
- Now since the .NET runtime has information about the TYPE of each object, it can calculate the size of each object and hence the block of heap memory it occupies. For all the marked objects, it leaves the block of memory occupied as it is.
- The rest of the memory is freed, compacted and the if necessary the other objects are relocated(and their addresses updated).
Am I correct in my understanding?