Detecting .NET Memory Leaks with WinDbg

Jul 11, 2024

Detecting .NET Memory Leaks with WinDbg

Introduction

  • Demonstration of a technique in WinDbg to detect .NET memory leaks.
  • Memory dump loaded in WinDbg contains a memory leak.
  • Program written to create objects and leave them in memory to illustrate memory leaks.
  • Source code available on GitHub.

Understanding .NET Memory Leaks

  • Technically, .NET cannot have a 'leak' as unmanaged code does.
  • 'Memory leaks' in .NET refer to objects with lingering references causing them to not be garbage collected.
  • Objects may remain in memory due to events or complex references.

Initial Setup

  • Ensure symbols are configured in WinDbg (refer to a related video or Google for details).
  • Load the SOS plugin using the command: loadby sos clr.

Steps to Identify Memory Leaks

  1. Dump Heap Statistics: Use dumpheap -stat to generate a histogram of objects in memory.
    • Identify objects with excessively high counts or sizes.
    • For illustration, the object is named leaky data.
  2. Analyzing Objects:
    • Use the method table from the dumpheap output to list instances of an object.
    • Commands: dumpheap /d <method_table> and !gcroot <address>.
    • This shows roots or references keeping the object alive in memory.
  3. Example Demonstration:
    • Analyzing leaky data object and finding its root using !gcroot shows its retention path.
  4. Investigate Event Handlers:
    • Event handlers are common sources of memory leaks due to lingering references.
    • Same dumpheap and !gcroot commands applied to event handlers.
    • Identifies connections between leaky objects and event handlers.

Additional Tools and Techniques

  • EE Heap: !eeheap -gc to examine memory distribution across generations and large object heaps (LOH).
    • Details on generations (0, 1, 2) and large object heap for handling larger objects.
    • To be covered in a future video.
  • Finalizer Queue:
    • Check for objects waiting for finalization using !finalizequeue.
    • Objects in this queue are marked for cleanup but still in memory due to unfinished finalizers.

Conclusion

  • Regularly repeat the process of analyzing suspected objects and finding their roots to identify leaks.
  • Engage with the content: comments, subscriptions, and thumbs up/down feedback.
  • Future content will delve deeper into advanced topics like EE Heap and large object heap debugging.

Final Notes

  • Stay tuned for more detailed videos on .NET debugging techniques.
  • Feedback and topic suggestions encouraged to tailor future videos.