Exception in a stupid program

I am using VS 2010.
When I run this program in debug mode, it throws an exception and shows the line in the chkstk.asm file on line 99.
But when I run it in Release mode, everything is fine.
Also, if I reduce the size of one of the arrays to 10,000, 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; } 
+6
source share
4 answers

Since the stack is quite small, about 1 MB on most systems, you overflow it with your large buffers. To fix this, simply 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; } 
+11
source

The stack is pretty small (~ 1 MB). You fill it with a huge number of elements in these arrays.

If you need more space, try allocating a bunch (which pointers do).

A good way to implement this with vectors that internally store things on the heap:

 std::vector<char> w (1000001); std::vector<char> temp (1000001); 
+5
source

You push too many things onto the stack; probably in debug mode the stack is more busy due to various security checks or intentionally less to help you detect such problems earlier. Be that as it may, creating smaller arrays will lead to a stack overflow even in release mode (unless the compiler optimizes them at all).

The root of the problem here is that you should not allocate large things on the stack, which is quite limited in size (by default 1 MB on Windows with VC ++) and should only be used for small buffers / objects. If you need to make large allocations, make them on the heap (with new / malloc ), preferably using smart pointers to avoid memory leaks.

+5
source

Arrays in automatic storage are allocated on the stack. Stack size is limited. If there is not enough stack space to allocate automatic variables, an exception is thrown.

If you need large arrays, use static or dynamic allocation instead.

For static distribution, move declarations to external main() .

For dynamic allocation, use the following code:

 char *w = new char[1000001], *temp = new char[1000001]; // Work with w and temp as usual, then delete[] w; delete[] temp; 

Finally, consider using standard containers instead of simple arrays: std::array is the best array if you do not need to resize (it is allocated on the stack and will not solve this problem); std::string also a good candidate for replacing char arrays.

+4
source

Source: https://habr.com/ru/post/915443/


All Articles