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.
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.
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