Having large 2d arrays: static int vs int

While resolving a DP-related problem, I noticed that it worked first, but a second time. What is the actual reason and what is the memory limit for using int?

int main(){ static int a[3160][3160]; return 0; } int main(){ int a[3160][3160]; return 0; } 
+4
source share
2 answers

Since you probably don't have enough stack memory to store this large array.

The second example creates an array on the stack, while the first example creates an array that is not on the stack, but somewhere in the data / Bss segment, because you explicitly specify storage criteria using a static classifier.

Note that the C ++ standard does not specify stack or heap or data segment or Bss segment , these are all the details defined by the implementation. The standard defines only the behavior expected from variables declared with different storage criteria. So, where the variables are actually created, the implementation is implemented, but, of course, one, both examples will create arrays in different areas of memory, and the second because of failures, because there is not enough memory in this region.

In addition, it is possible if you create an array of such huge sizes in a real implementation, your design seems erroneous, and you can think about revising it.

You might also consider using std :: array or std :: vector instead of traditional c-style arrays.

+5
source

Allocating a stack that is not safe (if you have not fulfilled this guarantee).

The stack size depends on the platform / equipment. Therefore, the "memory limit" changes dramatically. If you use huge stack arrays like this, be prepared to see this error often when your program runs on a processor other than the one you use for development. If you absolutely need a large stack, you must create your own threads with an explicit stack size.

However, this measure is not needed because you should just use dynamic allocation here.

static not a good choice if you need it to be reentrant.

As Als (+1) noted, the cause of the runtime error is most likely the size of the stack.

+1
source

Source: https://habr.com/ru/post/1393592/


All Articles