Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
Aurus Avatar asked May 14 '12 16:05

Aurus


1 Answers

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).

like image 93
Seth Carnegie Avatar answered Oct 19 '22 03:10

Seth Carnegie