Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Difference between global and non-global arrays (Stackoverflow Exception) [duplicate]

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 enter image description here

like image 542
Varun Sharma Avatar asked Jan 10 '23 23:01

Varun Sharma


1 Answers

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;
}
  • Automatic storage is allocated at a mix of compile time/run time. The stack expands at run-time entry to a function in order to hold local variables, but this is a known compile-time value since the number of variables and their sizes are well known (I'm ignoring dynamic arrays here because they are non-standard) These variables are constructed on scope entry, and destructed on scope exit.
  • Static storage is allocated at compile time. This memory is paid for up front, and constructed at program start. It is destructed when the program exits.
  • Dynamic storage is allocated at run-time. This memory is allocated by 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.
like image 103
Sam Cristall Avatar answered Jan 23 '23 11:01

Sam Cristall