A clear understanding of the .NET Garbage Collector awaits you…
Delphi compiler engineer Barry Kelly explains the inner workings of the .NET garbage collector (GC) clearly and succinctly. Here’s a snippet from his excellent article:
We all know what the gist of GC is about: you allocate new objects, but don’t have to worry about freeing them. Combined with type safety in the language, this can give you another kind of guarantee, memory safety: that it’s impossible to create a dangling pointer (a pointer to freed memory). Type safety’s "safety" is compromised in the absence of memory safety. For example, in a type-safe yet non-GC language, if you allocate an object, make a copy of the reference, then free the object, you’re left with a dangling pointer. If you then reallocate another object with a similar size, depending on the memory allocator’s implementation, you may have actually created a type hole – the dangling pointer may now point to the newly allocated object but with the wrong type. This extra safety is one of the reasons why GC programs often have less bugs than ones using manual allocation.
Whether you have interest in .NET or not, this article is well worth your read because many of these same principles (e.g. generational garbage collection) apply to gc’s found in other virtual machines, including the Java Virtual Machine.