Stefan Radulian
Stefan Radulian

Reputation: 1436

GC and application roots

The jit compiler and clr maintain a list of application roots that either point to objects in the heap or are null. The GC creates a graph out of these roots and marks all objects in the heap that are referenced in this graph - the rest is garbage.
My question is: how do the roots become null?
The obvious case is when a variable is explicitely set to null in the code. But what if not? How does the jit/clr know when to set a root to null?

Upvotes: 1

Views: 900

Answers (1)

Matt Redmond
Matt Redmond

Reputation: 11

My understanding is that the pointers contained in the application roots aren't set to null. This is a bit counter-intuitive (IMHO) because it does seem like the fastest way to dispose of an object would be to simply get rid of the pointer to it, much like the FAT file system simply marks a FAT entry to delete a file, without actually following that 'pointer' out to the bytes on disk and setting them to zero. I missed an interview question that touched on this so I read a bit about it, even though it has precisely zero applicability to anything we worry about on a daily basis.

In any case... Jeffrey Richter wrote an MSDN article twelve years ago addressing this. It is from his article that I learned the following.

When the GC runs it assumes all of the application roots point to unreachable objects. It walks the roots, following them to objects on the heap (or discovering that they don't point to anything valid). It does this recursively, building a new graph of reachable objects. Then it walks the heap, moving valid objects down and fixing up their pointers - the effect of which is to consolidate the free memory at the top of the heap. At some point in this process the graph of reachable objects is copied back to the application roots, replacing them. I am unsure if this happens before or after the heap is compacted.

The Dec '12 and Jan '13 issues of MSDN Magazine also contain an article on C# memory management. I haven't read it but plan to - it might clarify all of this.

Upvotes: 1

Related Questions