Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack overflow - static memory vs. dynamic memory

If you write int m[1000000]; inside the main function of C/C++, it will get a runtime error for stack overflow. Instead if you write vector<int> m; and then push_back 1000000 elements there, it will run fine.

I am very curious about why this is happening. They both are local memory, aren't they? Thanks in advance.

like image 508
smilitude Avatar asked Nov 29 '22 11:11

smilitude


1 Answers

Yes, the vector itself is an automatic (stack) object. But the vector holds a pointer to its contents (an internal dynamic array), and that will be allocated on the heap (by default). To simplify a little, you can think of vector as doing malloc/realloc or new[] calls internally (actually it uses an allocator).

EDIT: As I noted, automatic variables are allocated on the stack, while malloc generally allocates on the heap. The available memory for each are platform and even configuration-specific, but the available stack memory is typically much more limited.

like image 121
Matthew Flaschen Avatar answered Dec 08 '22 23:12

Matthew Flaschen