"Reading notes" C # Advanced Programming chapter 14th memory management and pointers

Source: Internet
Author: User

(a) Background memory management

1. Value data type

Windows uses a virtual addressing system that maps the memory addresses available to the program to the actual address in hardware memory, which is managed in the background by Windows (32 bits per process can use 4GB of virtual memory, 64 bits More, this memory includes executable code and loaded DLLs, and the variable content that the program uses when it runs).

In the virtual memory of the processor, there is a region called the stack. The stack store is not a value data type for an object member.

When you release variables, the order is always the opposite of the order in which they allocate memory, which is how the stack works.

The first time the program runs, the stack pointer points to the end of the memory block reserved for the stack. The stack is actually filled down, which is populated from a high memory address to a low memory address. When the data is in the stack, the stack pointer is adjusted to always point to the next idle cell.

2. Reference data type

The managed heap uses a method (the new operator) to allocate memory, and the data stored in it is still available for a long time after the method exits. Unlike stacks, the memory on the heap is allocated upward.

The process of establishing a reference variable is more complex than establishing a value type, and it does not avoid the overhead of performance. When a reference variable goes out of scope, it is removed from the stack, but the referenced data remains in the heap until the program terminates and the garbage collector deletes it, and it is deleted only if the data is no longer referenced by any variable.

3. Garbage collector

The garbage collector releases all objects that can be freed, moving other objects back to the end of the heap, forming a contiguous block again.

The first part of the heap is called the No. 0 generation, and the new objects created are moved to this section. After each run, the garbage collector retains objects that are compressed and moved to the next-generation storage section.

Under. NET, the larger object has its own heap, called the Elephant heap. When you use an object that is larger than 85,000 bytes, they are placed on this particular heap.

The second generation and garbage collection on the elephant heap is now placed on a background thread.

The Gcsettings.latencymode property can control how the garbage collector does garbage collection.

(ii) Release of unmanaged Resources

The garbage collector does not know how to release unmanaged resources (file handles, network connections, database connections), and requires specific rules to ensure that unmanaged resources are released when an instance of the class is reclaimed.

    • Declares a destructor (or finalizer), as a member of a class
    • Implementing the IDisposable interface

1. destructor

destructor syntax, no return type, no parameter, no access modifier, preceded by a tilde (~) with the same name as the class.

class myclass{    ~MyClass () {        // destructor     }}

The C # destructor cannot determine when to execute. The implementation of the C # destructor delays the time at which the object will eventually be removed from memory.

2. IDisposable interface

In C #, we recommend using the System.IDisposable interface instead of destructors. The IDisposable interface declares a disposable () method, which returns void without parameters.

class myclass:idisposable{    publicvoid  Dispose ()    {        // Release     }}

Call the Dispose () method:

New MyClass (); // code My. Dispose ();

In this way, if an exception is thrown in the procedure code, theDispose () method is not called, causing the memory to not be freed.

New MyClass (); Try {    // code }finally  {    My. Dispose ();}

The above method can avoid the exception of the procedure Code, which causes the memory not to be released. You can also use the Using keyword to simplify the call, the same effect as above.

using New MyClass ()) {    // code }

(iii) Unsafe code

1. Direct access to memory with pointers

A pointer is simply a variable that stores an address in the same way as a reference.

(1) Use unsafe keyword to write unsafe code

Unsafe code is used by the keyword.

unsafe classMyClass//Unsafe Class{    unsafe  Public stringName {Get;Set; }//Unsafe Properties    unsafe voidSayhi ()//Unsafe Methods{Console.WriteLine ("hi!"+Name); }    voidSaybay () {unsafe int* PAGE;//Unsafe Local variables need to be in unsafe methods, here will be an errorConsole.WriteLine ("bye!"+PAge); }}

(2) syntax for pointers

After you mark the code block as unsafe, use the following syntax to declare the pointer:

int* age;

After declaring variables of pointer type, you can use them in the same way as normal variables, but first you need to learn two more operators:& means "fetch address", * means "get the content of the address".

int Ten ; int* PX = &x; int y = *px;

You can declare pointers as any type of value.

(3) Casting the pointer to an integer type

Because the pointer actually stores an integer representing the address, any address in the pointer can be converted to and from any integer type.

int  - ; ULONG* PY = (ulong*) x;

It is important to note that on a 32-bit system, where an address is 4 bytes, converting a pointer to a non-uint, long, or ulong can cause overflow errors, a 64-bit system with an address of 8 bytes, and an overflow error when the pointer is converted to non-ulong. Also note that the overflow of pointers cannot be checked by the checked keyword. Because. The NET runtime assumes that you do not have to worry about overflow if you use pointers to know what you are doing.

(4) Casting between pointer types

byte Ten ; byte* PB = &b; Double* PD = (double*) PB;

(5) void pointer

byte Ten ; byte* PB = &b; void* PV = (void*) PB;

The primary function of the void pointer is to invoke an API function that requires the void* parameter.

(6) Arithmetic operation of pointers

You can add and subtract integers to the pointer. A pointer to type T is given a value of X, where the value of the pointer is P, then the resulting result is p+x* (sizeof (T)).

byte Ten ; byte* pB = &b;pb--;

If two pointers are of the same type, you can subtract one pointer from another, and the result is a long value that is the result of dividing the two values by the number of bytes of the type.

byte Ten ; byte* pB1 = &B1; byte  One ; byte* pB2 = &B2; long l = PB1-PB2;

(7) sizeof operator

Using the sizeof operator, its argument is the name of the data type, returning the number of characters that the type occupies.

int sizeof (int); // 4

(8) struct pointer: pointer member access operator

Structure pointers work exactly the same way as pointers to predefined value types. But there is one condition: structs cannot contain any reference types, because pointers cannot point to any reference types.

mystruct* pstruct; MyStruct mystruct=new  mystruct ();p struct= &mystruct; // accessing struct member values through pointers 4 ; // Another type of syntax 4;

(9) Class member pointers

You cannot create a pointer to a class because the garbage collection period does not maintain any information about the pointer, maintains only information about the reference, and the heap is moved during garbage collection, which causes the pointer to point to the error, and in order to solve the problem, the fixed keyword is used to tell the garbage collector that Do not move these objects.

New MyClass (); fixed (double* PX = & (Myclass.x)) // multiple Such pointers can be placed before a block of code to put more than one fixed (long* PX = & (MYCLASS.Y), PZ = & (MYCLASS.Z)) // can be declared within one parenthesis when the pointer type is the same {    fixed (long* pw& (MYCLASS.W))// nested declaration     { }}

2. Use pointers to optimize performance

1. Creating a stack-based array

One of the main areas of application of pointers: creating high-performance, low-overhead arrays in stacks. To create a high-performance array, you need to use another keyword: stackalloc. stackalloc command Prompt. NET runtime allocates a certain amount of memory on the stack (the number of bytes in the data type multiplied by the number of items). When invoking the stackalloc command, you need to provide the data type to be stored (must be a value type) and the number of data items that need to be stored.

decimal stackalloc decimal [ten];

The number of items can also be a variable:

int 5 ; decimal stackalloc decimal [Size];

Stackalloc always returns a pointer to the assigned data type, which points to the top of the newly allocated memory block.

To access the next element of an array, you can use the pointer algorithm. Use the expression * (pdecimal+x) to access the element labeled X in the array.

1; // Array Item 1th 1 2; // Array Item 2nd C # also defines another way to access an array, in the same way as normal array access. pdecimal[01; // equivalent to *pdecimal = 1; pdecimal[12// equals with * (Pdecimal + 1) = 2;

It is important to note that when using pointers, the compiler cannot check for variables, which throws an exception at run time when the number of access items exceeds the number of items allocated.

pdecimal[;

Using pointers while getting high performance also pays a price: you need to make sure you know what you're doing, or you'll throw a very odd run-through error.

"Reading notes" C # Advanced Programming chapter 14th memory management and pointers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.