0

Any recursion can be modified to be a iterative function with stack structure, then why do I ever want to do that? If the answer is to avoid stackoverflow, then how come computer can overflow by recursion at all? why not compiler automatically put a recursion function on a stack in heap by default or with an additional keyword? I understand heap is also limited, but it is much bigger than stack allocated to a program.

user40129
  • 763
  • 1
  • 5
  • 15
  • 3
    Heap isn't infinite either... – Joachim Isaksson Oct 23 '13 at 04:35
  • 2
    [Tail-recursive functions](http://stackoverflow.com/questions/33923/what-is-tail-recursion/33928#33928) can be re-written as iterative functions but many recursive functions are not tail-recursive. – Simon Oct 23 '13 at 04:35
  • Every process has got 4GB of virtual memory on a 32 bit computer out of which 2GB is assigned to Operating System data structures. Hence the stack is limited in size and can overflow. – Tushar Jadhav Oct 23 '13 at 04:39

3 Answers3

0

Activation records can indeed be heap allocated, but this is usually considered too expensive. Despite that there are a few implementations which take this approach: Stackless Python and SML/NJ, for instance.

In those cases the motivation is probably aiding the implementation of continuations, not "fixing" stack overflow.

gsg
  • 9,167
  • 1
  • 21
  • 23
0

According to C/C++ maximum stack size of program and MSDN, the maximum stack size on Windows is 1 MiB. Your question is interesting. A keyword would certainly be possible and the compiler could do it. You need to ask compiler makers about it, but I guess it is not a very interesting feature.

Caching would be difficult because of other local variables lying on the stack and recursion book-keeping variables on the heap. Information is scattered around in memory.

Some recursive algorithms can be turned into truly iterative ones (like the calculation of the Factorial) or even into a closed-form expression (see for example the Fibonacci numbers). Then, there is no need for book-keeping of recursive calls.

Community
  • 1
  • 1
AKo
  • 61
  • 5
0

In an iterative process you keep track of recursion state yourself.

It is possible that you can do this more efficient then the compiler can with the very general procedural mechanism (whose efficiency can be hampered by all kinds of ABI concerns).

Stack checking is possible, but not easy on all systems, since not all systems employ a fixed stack or linear address space. It also has an overhead of course, since the check is added to each recursion.

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89