+ 3
Why do we need a heap if it's memory address is in stack?
3 Respuestas
+ 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.
+ 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).
+ 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.