Stack Overflow - Static Memory and Dynamic Memory

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

I am very curious why this is happening. They are both local memory, right? Thank you in advance.

+4
source share
4 answers

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

EDIT: As I noticed, automatic variables are allocated on the stack, and malloc usually allocated on the heap. The available memory for each of them is a platform and even specific to the configuration, but the available stack memory is usually much limited.

+12
source

Stack memory is limited because it must be reserved in advance. However, heap memory is typically spent on much higher limits imposed by your OS, but "almost" reaches the limits of your virtual address space (2 GB for a 32-bit machine, much more for a 64-bit machine).

You can increase the amount of reserved stack space, usually as a parameter for your linker.

+6
source

int m [1000000] - it will allocate 1000000 ints on the stack . since the stack is limited, so it will cause a runtime error.

vector m; and then a push_back of 1,000,000 elements works because the internal vector allocates memory on the heap not on the stack . therefore, only a vector object is present in the application stack, so it does not throw a runtime error.

+5
source

The vector object itself is on the stack; but internally it will allocate memory from the heap as necessary to store a harsh number of elements. Thus, the cost of the stack is small and fixed for it.

+1
source

All Articles