In C++ there are two ways one can declare an object. For example:
// The first way
vector<int> *nums = new vector<int>;
// The second way
vector<int> nums;
People say that the first declaration allocates the object in the heap and the second on the stack. I can imagine how it works if the vector object is in the heap. The compiler would just find a free block in the heap to store the vector. But what would happen if the object is allocated on the stack as I keep pushing new elements to the vector? Will there be enough memory space? If not, how would the compiler find a sufficiently big memory block on the stack to store the vector when the size of the vector can change?
The allocation and deallocation for stack memory is automatically done. The variables allocated on the stack are called stack variables, or automatic variables. Since the stack memory of a function gets deallocated after the function returns, there is no guarantee that the value stored in those area will stay the same.
Java Heap Space is used throughout the application, but Stack is only used for the method — or methods — currently running. The Heap Space contains all objects are created, but Stack contains any reference to those objects. Objects stored in the Heap can be accessed throughout the application.
Because the data is added and removed in a last-in-first-out manner, stack-based memory allocation is very simple and typically much faster than heap-based memory allocation (also known as dynamic memory allocation) typically allocated via malloc .
C language provides the alloca function to allocate arbitrary size array on the stack. After the function returns or the scope ends, the stack memory is automatically reclaimed back (popped back) without the developer having to deallocate it explicitly and thereafter is unsafe to access it again from another function.
Putting vector
object on stack doesn't mean it will put its elements on stack. Check documentation:
Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it.
From: http://www.cplusplus.com/reference/vector/vector/
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