#929 – Visualizing How Objects Are Removed from the Managed Heap

Suppose that you create two Dog objects as follows.  (The BestFriend property refers to another dog that is the first dog’s best friend).

            Dog myDog = new Dog("Kirby", 15);
            myDog.BestFriend = new Dog("Jack", 17);

The managed heap now looks as follows:


Now suppose that you then execute the following lines of code:

            Dog yourDog = new Dog("Bowser", 3);
            yourDog = new Dog("Hank", 5);

Now the managed heap looks as follows:
At this point, let’s assume that the Garbage Collector runs, in an effort to reclaim some memory. Notice that the Bowser object is no longer referenced by any reference-typed variable or by another object. Bowser gets marked for collection:


All objects not marked for collection are compacted, moving them to the front (left) of the heap.  After the Garbage Collector runs, the heap is as shown below.  Note that the memory for the Bowser object is reclaimed by the heap.



About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #929 – Visualizing How Objects Are Removed from the Managed Heap

  1. Steven says:

    Nice explanation & diagram. Thanks for your time, Sean!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: