Reputation: 231
I have a question As far as I know , if I will receive a lot of elements , and put them in the stack , the process might crash , Heap should be safer and larger , so , when I allocate vector v , and insert elements, they will be stored at the Heap as answered in other topics right? So my program cant crash with long inputs, right?
Also , what does it mean the vector is in the heap , isn't the vector object is just a pointer to the first address containing the elements, in addition to some other functions
Upvotes: 2
Views: 1275
Reputation: 311116
Objects of std::vector are created in the stack (or static memory) if you will not intentionally create them in the heap using operator new. But items that the vector contains are created in the heap. When for example you define a vector the following way in some function
std::vector<int> v( 100 );
then variable v is placed in the stack. However the object itself that is v allocates one extent of heap large enough that to accomodate 100 elements of type int.
You can use operator sizeof that to determine how much memory occupies object of type std::vector itself. try this code
std::vector<int> v( 100 );
std::cout << sizeof( v ) << std::endl;
As you will see the size of an object of type std::vector does not depend on how many items the object can manipulate.
Upvotes: 7
Reputation: 5766
If you're handling a lot of data, and if you don't know exactly how much there will be, then heap storage is usually the correct choice. Your program can still run out of memory though if you try to use too much (it's a finite resource). Typically, that will result in a bad_alloc
exception being thrown, but if you don't catch and handle it then your program effectively crashes. Exactly how much memory is available depends on a lot of factors, including Operating System, hardware, and compiler configuration.
You're correct that the standard vector
class usually stores data on the heap, although the object itself may be on the stack (depending on how you've declared it). Internally, you can think of it like a dynamic array (allocated with new []
) which gets reallocated when necessary. Strictly speaking it may not be implemented exactly that way, but functionally it's analogous.
Upvotes: 1