+ 3

Why do we need a heap if it's memory address is in stack?

2nd Sep 2016, 3:57 PM
Munindra
Munindra - avatar
3 Respostas
+ 9
Because stack is static memory that means somewhere it has fixed size. Whereas heap is a dynamic memory that creates a memory on run time. And also using stack we can not achieve state management because whenever execution is completed stack is washed out but heap doesn't. We need to store the reference of object so that to tell from where CLR(runtime environment) should start the execution.
27th Sep 2016, 9:12 PM
Jai Verma
Jai Verma - avatar
+ 5
In stack is the address of object (not actual object). Objects are stored in heap because heap can grow and shrink (stack can not).
3rd Sep 2016, 5:03 PM
Omer SALAJ
Omer SALAJ - avatar
+ 2
Excellents points ... objects are always allocated memory on the heap. The heap is the memory available to a program at runtime for dynamic memory allocation. In contrast, some data items can be created on the execution stack or the call stack. Items created on the stack are the method parameters and the local variables declared within a method. The stack memory is reclaimed when the stack unwinds (when a method returns, for example). The memory allocated in the heap is automatically reclaimed by the garbage collector when the objects are not in use any more, for example no other objects are holding a reference to them.
7th Nov 2016, 4:34 AM
Gena Beamon
Gena Beamon - avatar