1

Why int array[1000][1000] is memory issue in C program when it is declared in main method instead of global declaration?

KiaMorot
  • 1,668
  • 11
  • 22
  • 4
    On most systems this would typically require 4 MB of stack space, so in some cases it will fail, as stack sizes can be anything from a few kB to several MB. – Paul R Sep 12 '14 at 08:45

1 Answers1

7

The stack has a limited size, and consequently can only hold a limited amount of information. If the program tries to put too much information on the stack, stack overflow will result. Stack overflow happens when all the memory in the stack has been allocated.

The program

int main()
{
    int array[1000][1000];
    return 0;
}  

tries to allocate a huge array on the stack.
Because the stack is not large enough to handle this array, the array allocation overflows into portions of memory the program is not allowed to use. Consequently, the program crashes.


Further reading: The stack and the heap.

haccks
  • 104,019
  • 25
  • 176
  • 264