We all know that it's good practice to create small methods that promote reuse, which inevitably will cause lots of methods being placed on the stack. However is it possible to reach the scenario where there are so many nested methods calls that a StackOverflow Exception occurs?
Would the accepted solution to be simply increase the stack size?
The documentation states that a such an exception will occur during "very deep or unbounded recursion" so it certainly seems possible, or does the .NET framework dynamically handle stack size for us?
My question can be summed up like so:
Is it possible to have such a well designed program (in terms of small reusable methods) that is becomes necassary to increase the stack size and hence use more resources?
The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack.
One method to prevent stack overflow is to track the stack pointer with test and measurement methods. Use timer interrupts that periodically check the location of the stack pointer, record the largest value, and watch that it does not grow beyond that value.
The stack size limit is the maximum size of the stack for a process, in units of 1024 bytes. The stack is a per-thread resource that has unlimited hard and soft limits.
A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. For example, suppose you have an app as follows: C# Copy. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }
The .NET stack size is fixed, and 1 MB by default.
Is it possible to have such a well designed program (in terms of small reusable methods) that is becomes necessary to increase the stack size and hence use more resources?
It will not be in the decomposition of your logic into methods.
The only way you'll encounter a Stack Overflow that is not a direct bug is with recursion. And when that happens (threatens), don't increase the stack but rewrite the code to use a different way to store data (like a Stack<T>
).
Not really. I just did a very quick test, and a StackOverflowException occurs after 15,000 nested calls.
There's no way you'll be writing code that will non-recursively nest 15,000 times due to the sheer number of methods you have.
Obviously the exact number depends on many function-local variables you have allocated on the stack. But whatever that actual number may be, it is nowhere near enough to do what you're suggesting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With