I'm reading about the C# garbage collector, and how the CLR builds object graphs. The chapter references different roots that could be active for the object:
• References to global objects (though these are not allowed in C#, CIL code does permit allocation of global objects)
• References to any static objects/static fields
• References to local objects within an application’s code base
• References to object parameters passed into a method
• References to objects waiting to be finalized (described later in this chapter)
• Any CPU register that references an object
I was wondering if someone could give examples of these roots in code?
Thanks
Assume you run the following program:
class Program
{
static Class1 foo = new Class1();
static void Main(string[] args)
{
Class2 bar = new Class2();
Class3 baz = new Class3();
baz = null;
Debugger.Break();
bar.Run();
}
}
When the program breaks into the debugger, there are 3+ objects that are not eligible for garbage collection because of the following references:
Class1
object referenced by the static field foo
string[]
object referenced by the parameter args
string
objects referenced by the string[]
object referenced by args
Class2
object referenced by the local variable bar
The Class3
object is eligible for garbage collection and may already have been collected or be waiting to be finalized.
References to global objects are not allowed in C#. References in CPU registers are an implementation detail of the VM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With