Circular References Cause Memory Leak?

GWLlosa picture GWLlosa · Dec 30, 2008 · Viewed 14.7k times · Source

I'm trying to run down a memory leak in a windows forms application. I'm looking now at a form which contains several embedded forms. What worries me is that the child forms, in their constructor, take a reference to the parent form, and keep it in a private member field. So it seems to me that come garbage-collection time:

Parent has a reference to the child form, via the controls collection (child form is embedded there). Child form is not GC'd.

Child form has a reference to the parent form, via the private member field. Parent form is not GC'd.

Is this an accurate understanding of how the garbage collector will evaluate the situation? Any way to 'prove' it for testing purposes?

Answer

Charles Bretana picture Charles Bretana · Dec 30, 2008

Great question!

No, Both forms will be (can be) GC'd because the GC does not directly look for references in other references. It only looks for what are called "Root" references ... This includes reference variables on the stack, (Variable is on the stack, actual object is of course on the heap), references variables in CPU registers, and reference variables that are static fields in classes...

All other reference variables are only accessed (and GC'd) if they are referenced in a property of one of the "root" reference objects found by the above process... (or in an object referenced by a reference in a root object, etc...)

So only if one of the forms is referenced somewhere else in a "root" reference - Then both forms will be safe from the GC.

only way I can think of to "prove" it, (without using memory trace utilities) would be to create couple hundred thousand of these forms, in a loop inside a method, then, while in the method, look at the app's memory footprint, then exit from the method, call the GC, and look at the footprint again.