Array size declaration~!

In C/C++ we always bound to declare array[] outside th main() function! I want to know the exact and relevant reason of that! In my point of view, declaring array[] outside main() would give you the opportunity of defining size up to 10e8… I want to know why it being said in gcc compiler?!!

note if one make static int arr[100000000] ,outside the main() ,then no compile error
but if int arr[100000000] in main() will compile time error

static memory is allocated once

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.

Storage for global variables is statically allocated in your computer’s virtual memory by the OS linker/loader at the time your program is loaded. The actual global variable storage is somewhere in the physical memory hierarchy (cache, RAM memory, SSD/HD backing storage, etc.), as mapped by the cache and VM system hence giving you the ability to store upto a greater extent.

The values of initialized globals are copied from the .data segment into a portion of the allocated virtual memory. Non-initialized globals might be zeroed, or might have junk left in them, depending on the security of the particular OS under which the program is running.

2 Likes

when you declare an array inside any function(main itself is an function) its scope is local to that function. Thus memory is allocated from stack (portion of memory alloacted to that function .) Thus, it can allocate till 10^5 or 10^ 6 and after that the stack overflows and you get SIGSEGV signal.

When you declare a global array, memory is allocated from heap which is a larger memory and thus you can get an array of 10^8. Static also helps because scope of static variables is lifetime of program. Thus memory is allocated once and so it is again allocated from heap.

Please note that even if you make an array inside, just preceeding it with static will let you make array of 10^7.

Now to get even more memory you can use a global vector or static vector and with vector you can get memory of about 10^9 .

Hope it helps

1 Like
//