Consider the following recursive function:
function fib (n:integer);integer; begin if (n=0) or (n=1) then fib := 1 else fib := fib(n-1) + fib(n-2) end;
The above function is run on a computer with a stack of bytes. Assuming that only return address and parameter are passed on the stack, and that an integer value and an address takes bytes each, estimate the maximum value of for which the stack will not overflow. Give reasons for your answer.
View worked solution
Answer: 16
To find the maximum value of for which the stack does not overflow, we first determine the size of a single stack frame and the maximum recursion depth.
- Stack Frame Size: Each stack frame stores the parameter (an integer) and the return address (an address).
- Maximum Recursion Depth: The longest chain of active recursive calls occurs along the left-most path of the recursion tree: The maximum number of active stack frames at any point during this execution is .
For a stack of bytes, the condition to avoid overflow is:
Thus, the maximum value of for which the stack will not overflow is 16.
Free practice · Your answers on this page are not saved.
