StackOverFlow Prevention in Recursive Functions

I have a recursive function in BaseClass that relies on a protected virtual function for a return condition.

It is possible that the child class incorrectly overrides this function and StackOverFlow exception. Worst of all, there are some slow network calls, and an exception will not happen soon (many resources spend for a long time).

I am looking for a way to test StackOverFlow early on somehow in a base class (possibly using Reflection and the current recursion level).

Any idea?

+8
reflection c # stack-overflow
source share
3 answers

You can pass the prime number "depth" to a recursive function and increase it with each subsequent call. If it becomes greater than the maximum allowable depth, throw an exception on the right, instead of waiting until it gets too late, and a terrible StackOverflow exception StackOverflow .

Such security mechanisms (increment counter, check that it is not stupidly large) can also be useful in while loops, where a small error can cause an infinite loop that consumes a huge amount of CPU.

On large systems with many users (such as websites), it is sometimes better to take precautions such as these with recursion and loops, since the consequences can go far beyond a single web page or system user. This is not a pretty code, and purists will undoubtedly refuse it, but it is efficient, secure and pragmatic.

+8
source share

Solve the problem, not create a workaround. Create a private function that is recursive that calls a protected virtual function.

+1
source share

Although you can probably read the call stack and parse it, I would not.

  • This will slow down the execution.
  • This is not the responsibility of your base class.
  • Document the behavior of your base class.

An alternative would be to perform call stack analysis only in DEBUG mode. Here is a little code to learn how to get a 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

0
source share

All Articles