Execution Stacks and when they Overflow
In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system. Normally, when you start your program, the compiler already breaks your program into independent threads which are passed to the runtime independently.
Each execution thread has a stack where local variables and arguments are allocated when a function or a method is invoked. A stack is used because it naturally follows the execution flow of method and function calls. The topmost record contains the data about the currently executing function; below that is the record of the caller of the function, which sits on top of another record of its caller, and so on.
In the example above, we have a function that calculates the factorial of a number n. Since this function is recursive, it does not compute the final result until the end condition n <= 1 is met. All preliminary result sets are held in memory and are contained in a stack that is bound to the currently executing thread.
e.g. the factorial of 5
In memory, our stack contains 5 variables, this is all good. A design-based question arises, how much information can this stack hold? We need to know this threshold to avoid the next error, the Stack Overflow exception.
Trying to calculate the factorial of n = 50000000 results in a Stack Overflow Exception - easily.