Stack memory is like a series of boxes with increasingly high heap. The call method is to put every parameter in a box and put it at the top of the stack. Each local variable is also allocated to a box and placed at the top of the stack. After the method is completed, all its boxes are removed from the stack.
Objects of the reference type are stored on the stack, which can be empty.
The heap memory is like a pile of boxes scattered in the room, and every box is strictly stacked on another box as the stack does. Each box has a label that indicates whether the box is in use. When creating a new object, runtime searches for an empty box and assigns it to the object. References to objects are stored in a local variable on the stack. Runtime will track the reference quantity of each box (multiple variables reference the same object ). Once the last reference disappears, runtime marks the box as "UNUSED ". At some point in the future, the items in the box will be cleared to make them reusable.
In addition, heap memory is a limited resource. If it is used up, the new operator throws an OutOfMemoryException and the object creation fails.
The Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace stack_heap
{
Class Program
{
Static void Main (string [] args)
{
}
Void Method (int param)
{
Circle c;
C = new Circle (param );
}
}
Class Circle
{
Public Circle (int)
{
}
}
}
When calling the Method, and passing the real parameter 8 to param:
1. First, the stack will allocate a small piece of memory (just to store an int) and use the value 8 for initialization.
2. Inside the method, another small piece of memory needs to be allocated from the stack, which can store a reference (a memory address ), only Initialization is not performed for the moment (it is prepared for variable c of the Cricle type ).
3. allocate a large enough memory area from the heap to accommodate a Circle object.
PS: The operation executed by the new Keyword --- it runs the Circle constructor and converts the original heap memory into a Circle object