Reputation: 2859
I'm trying to create stack overflow run-time exception with following program:
void f(int a) {
cout << a << ", ";
f(++a);
}
int main () {
f(0);
return 0;
}
When I run this program, my computer runs about 261824 call stack
then the command terminated
run-time error occurred. Now I want to know:
command terminated
error occur?try
, catch
stack overflow exception?call stack
?Upvotes: 2
Views: 572
Reputation: 275740
These are all implementation details. Technically a C++ implementation need not have a stack, it just needs automatic storage. There is at least one C implementation that used linked lists in the heap (well, sort of -- from what I understand, it is a strange system) for their automatic storage.
But, typically, the stack is a contiguous region of memory address space that the process reserves only for use to store automatic variables and call frames. It must be reserved prior to anything else happening, because it must be contiguous, and if some chunk of memory was allocated for another purpose, the stack would not be able to grow.
If you wanted to use your entire memory address space for the stack, there would be no room for the heap (aka, the free store). So the stack doesn't use all of memory...
1 MB is a traditional value to set the stack to: few programs really need more with even modest avoidance of putting large amounts of data on the stack. In multithreaded environments, each thread ends up with its own stack: so keeping it small also makes threads cheaper. Modern systems probably set it larger, because they have lots of address space for each process.
On 64 bit systems, it would be relatively easy to use 50 bits of address space for the stack (way more than your computer could currently handle: google data centers deal with petabytes). But the downside to this is you would only blow your stack while debugging after your entire system's virtual memory was grabbed by that one process. The upsides to this are not all that large.
The size of the stack is implementation defined, and not exposed by the C++ standard. See your compiler documentation for how to determine how big it is, and how to change its size.
The C++ standard does not dictate what happens when you blow your stack. In general, when the stack is blown, you are probably going to be in serious trouble: write code so that it doesn't happen, rather than catching it happen after it happens.
Upvotes: 6
Reputation: 8571
Upvotes: 4