Chapter 2 Memory Management
C # Memory Management provides the same Automatic Memory Management function as java, which frees programmers from heavy memory management. Memory Management improves code quality and development efficiency.
C # limits the use of pointers, eliminating the need for programmers to worry about memory leaks, but it does not mean that c # programmers cannot use pointers like java programmers. Microsoft considers this issue when designing the C # language. On the one hand, it discards pointers, and on the other hand, it adopts a compromise approach to introduce pointers when using a flag.
First, let's learn about Automatic Memory Management.
Public class Stack
{
Private Node first = null;
Public bool Empty {
Get {
Return (first = null );
}
}
Public object Pop (){
If (first = null)
Throw new Exception ("Cant Pop from an empty Stack .");
Else {
Object temp = first. Value;
First = first. Next;
Return temp;
}
}
Public void Push (object o ){
First = new Node (o, first );
}
Class Node
{
Public Node Next;
Public object Value;
Public Node (object value): this (value, null ){}
Public Node (object value, Node next ){
Next = next;
Value = value;
}
}
}
The program creates a stack class to implement a chain, and uses a push method to create a Node instance and a collector when the Node is no longer needed. A node instance is collected when it cannot be accessed by any code. For example, when a vertex element is removed from the stack, related nodes are collected.
The example
Class Test
{
Static void Main (){
Stack s = new Stack ();
For (int I = 0; I <10; I ++)
S. Push (I );
S = null;
}
}
For pointer reference, the unsafe flag is used in c # to reference the pointer of the representative team. The following program demonstrates the usage of pointers, but the memory management has to be done manually due to the usage of pointers.
Using System;
Class Test
{
Unsafe static void Locations (byte [] ar ){
Fixed (byte * p = ar ){
Byte * p_elem = p;
For (int I = 0; I <ar. Length; I ++ ){
Byte value = * p_elem;
String addr = int. Format (int) p_elem, "X ");
Console. WriteLine ("arr [{0}] at 0x {1} is {2}", I, addr, value );
P_elem ++;
}
}
}
Static void Main (){
Byte [] arr = new byte [] {1, 2, 3, 4, 5 };
WriteLocations (ar );
}
}