I'm using VS 2010.
When I run this program in the Debug mode it throws Stack overflow exception and shows a breakline in the file chkstk.asm at line 99.
But when I run it in the Release mode it's OK.
Also if I decrease the size of one of the arrays to 10000 it works well in Debug. What is the reason?
#include <iostream>
using namespace std;
int main()
{
char w[1000001], temp[1000001];
cout<<"Why?"<<endl;
return 0;
}
Setting the size of the stack or the maximum depth value of the recursion is allowed in most of the programming languages. Now that we have an opportunity to set the value of the depth of the stack, we have to set to a value as small as possible and observe the output.
A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }
StackOverflowError is a runtime error which points to serious problems that cannot be caught by an application. The java. lang. StackOverflowError indicates that the application stack is exhausted and is usually caused by deep or infinite recursion.
StackOverflowError is an error which Java doesn't allow to catch, for instance, stack running out of space, as it's one of the most common runtime errors one can encounter.
Because the stack is pretty small, approx 1MB on most systems, you're overflowing it with your large buffers. To fix that, just allocate on the heap like this:
#include <iostream>
using namespace std;
int main()
{
char* w = new char[1000001];
char* temp = new char[1000001];
cout<<"Why?"<<endl;
delete[] w;
delete[] temp;
return 0;
}
The stack is pretty small (~1MB). You're filling it up with the huge number of elements in those arrays.
If you need more space, try allocating on the heap (which pointers do).
A good way to implement this is with vectors, which internally store things on the heap:
std::vector<char> w (1000001);
std::vector<char> temp (1000001);
You are allocating too much stuff on the stack; probably in debug mode the stack is more occupied because of the various safety checks, or is intentionally smaller to help you detect such problems earlier. Anyhow, making the arrays a little bigger will trigger a stack overflow even in release mode (unless the compiler optimizes them out altogether).
The root of the problem here is that you shouldn't allocate big stuff on the stack, which is quite limited in size (1 MB by default on Windows with VC++) and should be used only for small buffers/objects. If you need to do big allocations, do them on the heap (with new
/malloc
), preferably using smart pointers to avoid memory leaks.
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