How memory is allocated for a variable declared outside vs inside main() How memory is allocated for a variable declared outside vs inside main() arrays arrays

How memory is allocated for a variable declared outside vs inside main()


When a variable is declared inside a function (in your case, main), it's allocated on the stack, and if it's too large (e.g, a big array), you'll encounter stack overflow.

A variable defined outside all functions is allocated statically. Its lifetime lasts until the program terminates.


It is implementation related issue. Theoretically defining a memory consuming variable should be possible in a function as same as global scope.

But in practice, the variables in global scope will be declared in data-segments of the target machine code and there is more available space to allocate. But, in the functions usually stack concept will be used which there is some limitations.


If it's local to a function (main is just another function) it goes on stack. 1000x1000x8 = 8 million bytes. That is probably larger than the stack size. Different compilers may have different sizes, but I think the default is 1MB.

Global variables (they have static storage) are not allocated on the stack, nor the heap, but on a data segment whose size remains constants throughout the programs duration.

Notice that a process has more than just two memory areas, stack and heap. It also has a code/text segment, a data segment for initialized static variables in the program and another data segment called bss segment for uninitialized static variables. For more see Anatomy of a Program in Memory.