Tip for Finding Memory Leaks in C#
03 Oct 2006There are many tools and techniques for finding memory leaks in managed code. Some involve sophisticated tools like the CLR Profiler. While I have found such techniques useful for bugs in the “wild”, I have found a simpler technique that smokes out these errors during development. It’s really two tips.
Use FxCop or the code analysis tool in VS 2005 Pro. It tells you so much about your code and finds objects that you forgot to dispose. Use it every day.
Put break points on your finalizers. If you write classes of any complexity, you likely have implemented the dispose pattern for these objects. If not, you likely should. Add asserts to the finalizers or use break points and run your program as normal. Did you hit any finalizers (you see this mostly during program exit)? If so, these are good candidates for further examination. It’s a good bet that if your finalizers are executing then your objects are living longer than they should.
Other interesting articles about Dispose Patterns