Resemble Memory Summary

xiaoxiao2021-03-06  63

Http://www.pconline.com.cn/pcedu/empolder/life/0405/373716_1.html

1. After using the Malloc or New to apply for memory, you should immediately check if the pointer value is NULL. Prevent memory using the pointer value of NULL.

2. Don't forget to pay initial values ​​for array and dynamic. Prevent memory that will not be initialized as the right value.

3. Avoid the subsidiaries of array or pointers, especially "more 1" or "less 1" operation occurs.

4. The application and release of dynamic memory must be paired to prevent memory leakage.

5. After released the memory with free or delete, set the pointer to NULL to prevent "wild pointer".

Let's take a few classic mistakes. Don't make the same mistake:

1. Return to the store memory pointer

Char * getString (Void)

{

Char * p = "Hello World";

Return P;

}

Char * pget = getString ();

There is no error in this program, but there is no error, but you can't make the data you want to point to the "Hello World" you want, because the pointer P's life is the function getString, run the function getString After the P-assigned stack space is immediately recovered. Although the PGET point to the Memory address allocated at the PGET, the address has no content.

2. This is a very high frequency error.

Char * pchar = new char;

......

Int a;

PCHAR = & A;

......

Delete pchar;

Of course, this is an example, and the specific procedures are different.

This process has two problems. First, PCHAR = & A; will lead to the original space that PCHAR is unable to be acquired, just like our mobile phone number, you can't contact this friend again. This causes memory leakage. If the memory is more, it may cause the system to crash because the available resources will be less and less until it is exhausted. The second problem is that delete pchar will result in an exception, because Pchar is not pointing to dynamically assigned memory, but pointing to a stack space allocated, and the stack space cannot be recycled with delete, so it will result in Memory exception.

Memory is wealth, correct use of wealth is the key, this is the case, the program is the same.

转载请注明原文地址:https://www.9cbs.com/read-84910.html

New Post(0)