When I write the following program, it works correctly i.e. the bitset array is declared outside the main() method.
Correctly Works
#include <iostream>
#include <bitset>
using namespace std;
bitset<5000> set[5000];
int main(){
cout<<"program runs fine"<<endl;
return 0;
}
But I get stack-overflow exception when I create it inside the main method. Can anyone explain in detail as to what is going on here? Normally I see stack-overflow exceptions in recursive methods. So who is using the stack here?
#include <iostream>
#include <bitset>
using namespace std;
int main(){
bitset<5000> set[5000];
cout<<"program runs fine"<<endl;
return 0;
}
Doesn't work and throws stack-overflow exception
Declaring it in main is declaring it in "automatic storage" AKA the stack. Declaring it outside of main, is declaring it in "static storage" AKA global data. You are declaring a ton of data. std::bitset<5000>
is 632 bytes on my system with VS2013 (likely an alignment from 5000/8). And you are declaring 5000 of them. 5000 * 632 = 3 160 000 bytes, or roughly 3 Megabytes. Default in VS2013 is 1 megabyte for the stack, which is why you are seeing an overflow.
There are three kinds of storage: automatic, storage, and dynamic. These are colloquially referred to as stack, static (in some cases, global) and heap memory respectively:
int static_int;
int main() {
int automatic_int;
static int local_static_int; // also static storage!
int * dynamic_int_ptr = new int;
}
new
and a pointer to some blob that holds your shiny new data is returned. These variables are constructed when new
is called, and destructed when delete
is called.