Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing StackOverFlow in recursive functions

I have a recursive function in a BaseClass which relies on a protected virtual function for it's return condition.

It's possible for a child class to override this function incorrectly and leads to a StackOverFlow exception. The worst thing is there are some slow network calls and the exception is not gonna happen soon (many resources waste for a long time).

I'm looking for a method to check StackOverFlow in early stages some way in the base class (maybe using Reflection and the current recursion level).

Any idea ?

like image 275
Xaqron Avatar asked Jan 28 '11 06:01

Xaqron


1 Answers

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.

like image 187
Ian Mercer Avatar answered Oct 05 '22 23:10

Ian Mercer