Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

arrays

memory

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?

like image 436
virtore Avatar asked Apr 30 '14 07:04

virtore


People also ask

Is memory allocated when a variable is declared?

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.

What happens in memory when a variable is declared?

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.

Is memory allocated during declaration or initialization?

Memory is allocated when a variable is declared, not when it's initialized.

How are variables stored in memory?

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.


1 Answers

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.

like image 120
Yu Hao Avatar answered Oct 19 '22 23:10

Yu Hao