Showing posts with label Managed code. Show all posts
Showing posts with label Managed code. Show all posts

June 17, 2006

Identifying Memory Leaks in Managed code

Q: Can you have memory leaks in managed code? If so, how can you catch them?

A: Garbage Collector will reclaim objects at its own pace, based on balancing available memory and runtime overhead. If an assembly is terminated and it is known to contain a significant percentage of total set of managed objects, then it is best practice to call GC.Collect() after the unload.

If we define a leak, as the memory usage grows over time, then it is possible to have leaks in a GC runtime. For example if you keep ever growing data in a static variable , an editor keeps an infinite undo list, then this can be be considered as a leak.

As far as leak detection and diagnosis, you should look at the performance counters in the category. In .NET CLR Memory, You will find a lot of interesting counters like #object in all heaps. They will tell you if you are leaking objects.

We should check out the various CLR memory profilers out there. by examinining them you can get a picture of the heap and by comparing the pictures at 2 different points you can determine which objects are accumulating, then find out which code path allocates them in the first place, or even, which connected graph keeps them alive.