Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect where a Memory Leak is?

I have a large website that seems to be sucking up all the memory that is being allocated. There is nothing else on the server beside this site. Within a week it eats away the 2 gigs and requires a restart. Currently this is server 2008 32 bit using IIS 7. We are reinstalling to use 64bit and add more memory. It would be nice to be able to track down where the leaks are occurring.

So what is the best practice to tracking memory leaks?

like image 712
Boone Avatar asked Sep 23 '09 02:09

Boone


2 Answers

Memory leaks in .NET are not that common, but when they happen it is most commonly due to unattached event handlers. Make sure you detach handlers, before the listeners go out of scope.

Another option is if you forget to call Dispose() on IDisposable resources. This may prevent cleanup of unmanaged resources (which are not handled by GC).

And yet another possible reason is a deadlocked finalizer. That will prevent all remaining objects in the finalizer queue from being collected.

I use WinDbg + Sos to track down leaks. The steps are as follows

  • Dump the heap and look for suspects
  • Use !gcroot to find out what is keeping the suspects alive
  • Repeat as necessary

Be aware that large memory usage may also be due to heap fragmentation. The regular heaps are compacted, but pinned objects can cause fragmentation. Also, the LOH is not compacted so fragmentation is not uncommon for LOH.

Excellent tutorials on WinDbg + sos here: http://blogs.msdn.com/tess/

like image 155
Brian Rasmussen Avatar answered Oct 12 '22 00:10

Brian Rasmussen


Run a profiler on your code.

Here are two good options:

RedGate's memory profiler

Jetbrains dotTrace

I believe both products have a free trial.

like image 28
Chris Ballance Avatar answered Oct 12 '22 00:10

Chris Ballance