Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack allocation fails and heap allocation succeeds!! Is it possible?

I have the following piece of snippet

Class Sample
{ Obj_Class1 o1;
  Obj_Class2 o2;};

But the size of Obj_Class1 and Obj_Class2 is huge so that the compiler shows a warning "Consider moving some space to heap". I was asked to replace Obj_Class1 o1 with Obj_Class1* o1 = new Obj_Class1(); But I feel that there is no use of making this change as heap allocation will also fail if stack allocation fails. Am I correct? Or does it make sense to make this change ( other than suppressing the compiler warning ).

like image 310
Prabhu Avatar asked Apr 22 '10 11:04

Prabhu


2 Answers

It is very typical that the stack is smaller than the heap. They use different memory locations. The stack is typically about a megabyte in size (you can change it, but be careful) and is allocated per thread. The heap can consume gigabytes if needed.

like image 73
Mark Byers Avatar answered Nov 01 '22 12:11

Mark Byers


The stack is usually small and not suitable to hold huge objects, while the heap is separate and designed for them.

In your sample, you should probably allocate the whole Sample on the heap, not its members:

int main() {
   Sample* sample = new Sample();
}
like image 45
Alexander Gessler Avatar answered Nov 01 '22 11:11

Alexander Gessler