Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stack-based object allocation

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?

like image 507
user3724417 Avatar asked Mar 18 '15 21:03

user3724417


People also ask

How is stack allocated in C?

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.

Are objects allocated on the heap or stack?

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.

Is stack memory faster than heap?

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 .

Are C arrays allocated on the stack?

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.


1 Answers

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/

like image 144
myaut Avatar answered Sep 22 '22 06:09

myaut