There is Run time error in making 2D Array

Viewed 117
using namespace std;

int dp[1001][1001];

int main() {

  ...
}

In this case, there is no run time error.

However,

using namespace std;

int main() {
   string A, B;

   cin >> A >> B;

   int dp[1001][1001];

   ....
}

If I make code like this, there is run time error. Even first line of main function didn't work.

Could you let me know why this error happend?

Thank you for reading my question.

2 Answers

When you declare a variable before main(), it is global variable, which is located in static memory. If you declare it inside main(), it is a local variable, which (in practice, although not mandated by C++ standard) is located on the stack. Only a small portion of the total memory is allocated to the stack. If you accede its size, you get stack overflow. That's what happened in your case, because int dp[1001][1001] typically takes about 4 MB or 8 MB, depending on sizeof(int).

When you initialize variable with global variable, computer saves it to heap.

however, local variables are saved in stack.

So

===

using namespace std;

int main() { string A, B;

cin >> A >> B;

int dp[1001][1001];

===

prints out an error. (int dp[1001][1001] is too big to save in the stack)

So, when you wanna save big variables in run-time (not global variable) just use 'dynamic allocation'. It also save variables to heap, and i think it will works.

Related