How to debug a stackoverflowexception in .NET

This is almost always due to recursion. Either a method calling itself, or a method calling a method that calls it back and so on.

To find it:

  • UPDATED: I didn't realise, but apparently you can't get the stack trace for a StackOverflowException (I guess something to do with not being able to catch one, either). However there are ways to get a dump as mentioned here.
  • ReSharper will show methods that call themselves (it puts a little green circle in the sidebar for recursive calls) though it won't catch recursion where two or more methods are involved.
  • Use a tool like ANTS Profiler to see which methods are called the most times.
  • Keep an eye out for events that fire that might call code that means the same event fires again, causing a loop.

Occasionally you'll get typos like this, too:

private string name;

public string Name
{
    get { return Name; } // Ooops! This is recursive, all because of a typo...
}

Which is one reason why I personally now prefer to use automatic properties.


You can execute the program on debug mode and pause it. On the current callstack you can see that there are a method or a group of method that appears several times, these are the problematic methods. Put a break point on this method and look what its calling itself all the time.


WinDbg can get the job done, including even getting a sensible (clr) stack trace. You'll need to get WinDbg unless you've already installed it with Visual Studio or Windows SDK. Note: "WinDbg Preview" with the new GUI has worked fine for me.

I suggest to start your process from WinDbg, but of course you can also attach it to a running process if this suits you better.

Note: Right after starting the process, the CLR is not loaded, and .loadby SOS.dll clr will fail ("unable to find module 'clr'). You have to wait for the CLR to be loaded. To stop execution once that happens perform:

  • sxe ld clr

Once the CLR is loaded you'll have to perform the following steps to break on StackOverflowException (enter in the command window / line):

  • .loadby SOS.dll clr (not .loadby sos clr—this can lead to the extension being loaded twice)
  • !stoponexception -create System.StackOverflowException
  • g (continues debugging)

trigger the StackOverflowException / wait for it to happen

  • !clrstack (will print the stacktrace)

Notable sources:

  • Riham Selim - Breaking on Module Load
  • Riham Selim - Breaking on Specific CLR Exception

Go to Debug, exceptions and check the thrown checkbox at 'Common Language Runtime Exceptions'. Now when you cause the stackoverflow exception, the debugger will stop (eventually) and show you the call stack.

Tags:

.Net

Debugging