Aurus
Aurus

Reputation: 705

c++ heap or stack allocation?

This is an allocation on the stack:

char inStack[10]; 
// and 
MyStruct cl;

And this should be allocated in the heap:

char* inHeap = new char[10];
// and
MyClass cl = new MyClass();

What if MyClass contains a char test[10] variable? Does this:

MyClass cl = new MyClass()

...mean that the 10 byte long content of MyClass::test is allocated in the heap instead of the stack?

Upvotes: 5

Views: 629

Answers (3)

The proper terms in the language are automatic and dynamic storage, and these make a bit more sense than stack and heap. In particular automatic storage does not imply stack in general, only in local variables in functions, but as you mention, if you are defining a member of a class, automatic storage will be wherever the enclosing object is, which can be the stack, the heap or a static object.

Upvotes: 2

Stephen Newell
Stephen Newell

Reputation: 7828

If MyClass has a char test[10] member, it will be allocated the same way the instance of MyClass was allocated.

MyClass mc; //mc.test is on the stack
MyClass * mcp = new MyClass; //mcp->test is on the heap

Upvotes: 5

Seth Carnegie
Seth Carnegie

Reputation: 75130

It would be allocated inside the object, so that if the object is on the heap, the array will be on the heap; if the object is on the stack, the array will be on the stack; if the object is in static memory in the executable, the array will be there also.

In C++, members of objects are part of the object itself. If you have the address of the object and it's size, you know that all the members of the class will be somewhere within the range [address, address + size), no matter where in memory that address actually is (heap, stack, etc).

Upvotes: 15

Related Questions