Why is array size limited when declared at compile time?

for example i can do

int *arr; arr = (int *)malloc(sizeof(int) * 1048575); 

but I can not do this without crashing the program:

 int arr[1048575]; 

why is that so?

+8
c memory-management arrays local-variables
source share
3 answers

Assuming arr is a local variable, declaring it as an array, it uses memory from the (relatively limited) stack, and malloc() uses memory from the (relatively unlimited) heap.

+11
source share

If you assign them as local variables in functions (this is the only place you could have a pointer declaration immediately after calling malloc ), then the difference is that malloc will allocate a piece of memory from the heap and give you its address, at that time as a direct execution of int arr[1048575]; will try to allocate memory on the stack. The stack has much less free space.

The stack is limited in size for two main reasons that I know of:

  • Traditional imperative programming uses very little recursion, so deep recursion (and the growth of a large stack) is "probably" a sign of infinite recursion and, therefore, an error that is about to kill the process. Therefore, it is best if it is caught before the process consumes gigabytes of virtual memory (in the 32-bit architecture), which will cause the process to exhaust its address space (at this moment, the machine probably uses much more virtual memory than it actually RAM, and therefore runs very slowly).
  • Multithreaded programs require multiple stacks. Therefore, the runtime system must know that the stack will never grow beyond a certain boundary, so it can put another stack after this binding if a new thread is created.
+2
source share

When you declare an array, you push it onto the stack.

When you call malloc (), memory is taken from the heap.

The stack is usually more limited than the heap and is usually transient (but it depends on how often you enter and exit the function declared by this array.

For such a large (perhaps not by today's version?) Memory, malloc it is a good practice, assuming you want the array to last a bit.

+1
source share

All Articles