How to avoid stack overflow in a recursive algorithm?

How to avoid stack overflow in a recursive algorithm?

To the general question of “methods to avoid a stack overflow in a recursive algorithm”… Another approach is to include a recursion counter. This is more for detecting infinite loops caused by situations beyond one’s control (and poor coding). Each time you make a call, you increment the counter.

How to rewrite a recursive function without a stack?

If your code uses tail recursion (that is, the function returns the result of every recursive call directly without any other processing) then it’s possible to rewrite the function imperatively without a stack: Into: Without tail recursion, using a stack (or a similar intermediary storage) is the only solution.

Can a function be written without tail recursion?

Without tail recursion, using a stack (or a similar intermediary storage) is the only solution. The classic recursive function that can be written as a loop is the Fibonacci function: But without memoization this takes O (exp^N) operations with O (N) stack space.

Can You rewrite a function in Fortran without recursion?

I’m rewriting some existing code in a setting where recursive calls are not easily implemented nor desired. (And in Fortran 77, if you must know.) I’ve thought about making a stack from scratch to keep track of the calls needed, but this seems kludgy, and I’d rather not allocate memory to an array in cases where the recursion is not deep.

What are methods to avoid stack overflow in a…?

If you are using a language and compiler that recognize tail recursive functions and handles them properly (i.e. “replaces the caller in place with the callee”), then yeah, the stack should not grow out of control. This optimization essentially reduces a recursive method to an iterative one.

How can I keep track of stack depth?

Non-portably, you can keep track of the depth using a static variable; if you know the maximum stack size, and how much stack each recursion takes, then you can check that the depth doesn’t exceed that. A lot of systems, like Linux and Solaris, you can’t know the maximum stack depth up front, since the stack is allocated dynamically.