C++ Array Declaration Stack Overflow Exception
Error: Stack overflow when declaring a huge array in C++.
Unhandled exception at 0x00007FF60B7040C8 in Tutorial.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000081A80D3000). occurred
Problem code:
#include <iostream>
#include <fstream>
int main()
{
//do something..
int nar[10000000];
//do something more..
return 0;
}
Solution:
#include <iostream>
#include <fstream>
int nar[10000000];
int main()
{
//do something..
//do something more..
return 0;
}
Explanation:
- Since it is declared global it is accessible globally.
- You do not have to explicitly delete this memory.
- This will put the array on heap and stack overflow will not occur.
References:
Unhandled exception at 0x00007FF60B7040C8 in Tutorial.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000081A80D3000). occurred
Problem code:
#include <iostream>
#include <fstream>
int main()
{
//do something..
int nar[10000000];
//do something more..
return 0;
}
Solution:
#include <iostream>
#include <fstream>
int nar[10000000];
int main()
{
//do something..
//do something more..
return 0;
}
Explanation:
- Since it is declared global it is accessible globally.
- You do not have to explicitly delete this memory.
- This will put the array on heap and stack overflow will not occur.
References:
This crash happens when a very large array is declared as a local variable. Locals live on the stack, which is small, so a big array there exhausts the stack and the program faults.
The fix is to allocate large buffers on the heap instead, for example with std::vector or new, which draw from the much larger heap. This is a common pitfall once sizes grow beyond a few thousand elements.
Comments
Post a Comment