2
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.

VietHTran
  • 2,233
  • 2
  • 9
  • 16
YiBangwon
  • 21
  • 2
  • 3
    It helps to say what the runtime error actually is. Although in this case it's pretty obvious. You are declaring an array too large for your stack. When you declared the array as global, it lives outside the stack. If you need it to exist only within the context of a stack frame, then you should allocate it dynamically. – paddy Oct 09 '20 at 03:18
  • If this is windows the default stack is 1 MB. 1001 * 1001 * 4 is larger than that. – drescherjm Oct 09 '20 at 03:19
  • You are asking for a 4 MB stack. If the platform you are running does not grow the stack as necessary (most likely using a MMU to do so) then you most likely are overflowing the stack. And here we are on SO talking about it. – natersoz Oct 09 '20 at 03:31
  • Thank you guys. It's really helpful to me. I love you guys and I love stackoverflow.com!! – YiBangwon Oct 09 '20 at 04:56

2 Answers2

2

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).

Eugene
  • 6,194
  • 1
  • 20
  • 31
  • *In static memory*. Can you please elaborate on static memory? Like if it is not on the stack then where it resides, if it is a global variable?. – Imanpal Singh Oct 09 '20 at 03:39
  • 1
    [Storage class specifiers](https://en.cppreference.com/w/cpp/language/storage_duration) -- 3rd time is the charm. – David C. Rankin Oct 09 '20 at 03:48
0

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.

seenblee
  • 52
  • 4