Difference between static short and short

The following code just works fine and gives what is expected

1
2
3
4
5
6
#include <iostream>
using namespace std;
int main(){  
 static short DP[6100][6105];
 cout << DP[5][5];
}

which is 0.

But the following code on the other hand.
#include <iostream>
using namespace std;
1
2
3
4
5
int main(){  
 short DP[6100][6105];
 for(int i = 0; i <= 6 ; i++)DP[i][i] = 0;
 cout << DP[5][5];
}

gives a segmentation fault.

Can someone please explain why?
I know that due to static keyword the array will hold the value between function calls. But here the main function is only called once, so does that matter.
Last edited on
When you don't use static it will store DP on the stack. The stack is usually very limited in memory so it runs out of stack space when you try to store such a large object.

https://en.wikipedia.org/wiki/Call_stack
Last edited on
Thanks a lot for the help Peter. I posted the same question on Stack Overflow and received a very hostile response from the community.
Thanks for the help here.
So basically all static variables are stored in heap just like dynamically initialized arrays?
While automatic variables are initialized on stack. Is that right?
So basically all static variables are stored in heap just like dynamically initialized arrays?
While automatic variables are initialized on stack. Is that right?


Disregarding variables with thread storage duration, C++ has variables with 3 types of storage duration: automatic duration, which corresponds to variables that reside on the stack; dynamic duration, which corresponds to variables that reside on the heap; and static duration which corresponds to variables existing for the entire length of the program. All 3 types are typically stored in different areas of memory, although there is no requirement to do so in the standard.
Topic archived. No new replies allowed.