Preventing StackOverFlow in recursive functions

旧巷老猫 提交于 2019-12-01 03:50:15

You could pass a simple integer 'depth' to the recursive function and increment it with each subsequent call. If it gets larger than the maximum allowed depth throw an Exception right then instead of waiting until it's too late and the dreaded StackOverflow exception has occurred.

Such safety mechanisms (increment counter, check it's not stupidly large) can also be handy in while loops where a small error can cause an infinite loop consuming vast quantities of CPU.

In large systems with many users (e.g. web sites) sometimes it's best to take precautionary measures like these with recursion and while loops because the consequences can reach far beyond one web page or one user of the system. It's not pretty code and the purists will no doubt balk at it, but it's efficient, it's defensive and it's pragmatic.

Solve the problem instead of creating a workaround. Create a private function which is recursive which calls the protected virtual function.

Although you probably can read the call stack and analyze it I wouldn't do that.

  1. It will slow down execution
  2. It is not your base class' responsibility
  3. Document your base class' behaviour

An alternative could be to do the call stack analysis in DEBUG mode only. Here is a little code to see how to get the call stack.

using System.Diagnostics;

[STAThread]
public static void Main()
{
  StackTrace stackTrace = new StackTrace();           // get call stack
  StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

  // write call stack method names
  foreach (StackFrame stackFrame in stackFrames)
  {
    Console.WriteLine(stackFrame.GetMethod().Name);   // write method name
  }
}

From this site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!