I have noticed when working with some large arrays (like doubles 1000 by 1000) that my program runs out of memory if I declare the array inside of main() but this never seems to happen if I declare the array outside main() even for larger arrays. Can someone explain what the distinction is?
When a variable is declared compiler automatically allocates memory for it. This is known as compile time memory allocation or static memory allocation. Memory can be allocated for data variables after the program begins execution.
Every time a function is called, the machine allocates some stack memory for it. When a new local variables is declared, more stack memory is allocated for that function to store the variable. Such allocations make the stack grow downwards.
Memory is allocated when a variable is declared, not when it's initialized.
Variables are usually stored in RAM. This is either on the heap (e.g. all global variables will usually go there) or on the stack (all variables declared within a method/function usually go there). Stack and Heap are both RAM, just different locations. Pointers have different rules.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With