views:

156

answers:

3

Hi,

What are the best ways for a .NET developer to hunt down (and avoid) unmanaged leaks in a managed app?

There seem to be many excellent resources for tracking down managed leaks, but I haven't found much on tracking unmanaged leaks in a managed app.

This question is related, but asks the question from a purely unmanaged point of view, so many of the answers assume that you have access to unmanaged code, and none mention any .NET-specific pitfalls or techniques.

Here are some (very basic) things I have tried:

  • DebugDiag. It looks very promising, and it may work for you, but it happens to crash my particular app.
  • Rational PurifyPlus. Sadly, also crashes my app.
  • AQTime (at the recommendation of @Reed and @Caelum). This program looks fabulous, but, like the poster of the question @Caelum mentioned, AQTime also crashes my app.
  • Temporarily remove code that creates objects that I know use unmanaged memory.
  • Ensure that the app is disposing all objects that implement IDisposable

I should mention that I was able to successfully profile another managed app (which was leaking unmanaged memory) using the profilers above. Please give them a try if you've got an unmanaged leak.

A: 

I think you have hit the majority of options, the best way I have found is simply to think about the how I am using and dispoising of unmanaged resources right from the start.

As you said, ensuring good use of IDisposable and thinking about finalizers and how they impact your application are the best ways I have found to avoid leaks in the first place :).

DebugDiag is what the Microsoft performance team will use when looking for problems with your application, and I believe taking memory dumps for it may even be integrated into task manager in Win 7 and Visual Studio 2010 as well.

When using DebugDiag be sure to look at the SOS extensions. Perhaps a better question would be to ask why DebugDiag and PurifyPlus are crashing for your particular app? As this seems like it will cause problems regardless of what you try...

Glenn Condron
You're right: finding a way to use these profilers is a very good idea. Even though my full app crashes when run via the profilers, I've had success profiling a small, leaky repro app.
IV
A: 

Personally, I use a code profiler that supports both managed and unmanaged (and mixed mode) code: AQTime. It will handle tracking memory from both managed and unmanaged code, so it makes tracking leaks in mixed projects much simpler

Reed Copsey