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

I noticed that when working with some large arrays (for example, it doubles 1000 per 1000) my program runs out of memory if I declare an array inside main (), but this never happens if I declare an array outside of main () even for large arrays . Can someone explain what the difference is?

+4
source share
6 answers

When a variable is declared inside a function (in your case main), it is allocated on the stack, and if it is too large (for example, a large array), you will encounter a stack overflow .

, , . , .

+6

, . , .

, . , .

+2

, , , . , main(), . ( ) , - ++, .


, , , automatic, , .

, , static , , .

. .

, malloc new. ( C, ++, - ++).

+1

(main - ), . 1000x1000x8 = 8 . , , . , , - 1 .

( ) , , , .

: , . /, , bss . . .

+1

, ( ) ( , , ), main puts , , ( ).

0
source

the stack size is about 2-3 M, and the heap size is associated with virtual memory. It can be very big. you can declare it as follows:static int num[1000][1000];

-3
source

Source: https://habr.com/ru/post/1538680/


All Articles