views:

127

answers:

4

Hello All,

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

+4  A: 

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.

Mark Byers
But the stack and heap grow against each other. Don't they?
Prabhu
@Prabhu: Yes, but the maximum stack size is still limited to smth like 1 megabyte.
sharptooth
@Prabhu: No, they don't. That's a good model of explanation for a computer science class, but in reality there's nothing forcing that model to be the one actually used.
Billy ONeal
+3  A: 

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();
}
Alexander Gessler
+2  A: 

In case of visual studio, each thread by default gets 1 MB space, and if you try to allocate more than that you will get a stack overflow error. Heap doesn't have this restriction and the amount of memory you can allocate depends on the largest continuous space available in your process virtual memory. So it is not very surprising that the stack allocation fails in case the objects are really huge.

Naveen
Nitpick: Stack overflow happens not when allocating more than the stack size, but rather when allocating more that the available stack size. I mean it will or will not fail depending on how much stack is used already.
sharptooth
+3  A: 

Stack is rather small by default: http://msdn.microsoft.com/en-us/library/ms686774(VS.85).aspx

The default size for the reserved and initially committed stack memory is specified in the executable file header. Thread or fiber creation fails if there is not enough memory to reserve or commit the number of bytes requested. The default stack reservation size used by the linker is 1 MB. To specify a different default stack reservation size for all threads and fibers, use the STACKSIZE statement in the module definition (.def) file. The operating system rounds up the specified size to the nearest multiple of the system's allocation granularity (typically 64 KB). To retrieve the allocation granularity of the current system, use the GetSystemInfo function.

Pasi Savolainen