Why does a large array declared in main give RE but not when declared globally?

I was solving the Highway Bypass question. I made an int array which would be of at most 500 by 500 size, and it was getting an RE on some cases. Solution

However when I declared the DP array and the safe array outside main (globally) it did not RE. What is the reason behind this? Is this a coincidence or is it just a better practice to declare global variables statically (in competitive programming)?

Always keep in mind that Whenever you declared a variable inside a function i.e., main() it’s allocated on the stack, and if it’s too big approximately 10e5, then 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.

It’s all about the concept of Operating system that handle variables declaration outside the main and inside the main()…

I hope you doubt would be cleared otherwise feel free to ask again!

All the variables declared inside a function (even if that function is main) are declared on the stack. Each process has a stack limit (the default for Linux is 8MB), so when you declared the matrix inside the main function you probably went over the limit. If you do however wish to avoid global variables, I advice you to use STL containers. Those are declared in another part of the memory called the heap.