Correct memory usage

Source: Internet
Author: User

For beginners, memory is a mysterious space. Most program errors are caused by improper memory usage, and some of these errors are hidden. Therefore, it is critical for the software to succeed to learn how to use the memory and understand the system's memory management methods.

First, we need to understand the memory allocation method. Generally, there are three memory allocation methods:

1. allocated from the static storage area. The program has been allocated when it is compiled, and the program exists throughout the entire runtime. For example, global variables and static variables.

2. Create a stack. When a function is executed, the storage units of local variables in the function can be created on the stack. When the function is executed, these storage units are automatically released. Stack memory allocation computation is built into the processor's instruction set, which is highly efficient, but the memory capacity allocated is limited.

3. Allocate from the stack, also known as dynamic memory allocation. When the program runs, it uses malloc or new to apply for any amount of memory. The programmer is responsible for releasing the memory with free or delete. The lifetime of the dynamic memory is determined by us. It is very flexible to use, but the problem is also the most.

For the above three allocation methods, we should pay attention to the memory life cycle:

1. the life cycle of the static allocation area is the entire software operation period, that is, from the software operation to the software termination and exit. This memory will be recycled by the system only after the software stops running.

2. the life cycle of the space allocated in the stack is related to the function and class of the variable. If it is a local variable defined in the function, its life cycle is when the function is called. If the function is completed, the memory will be recycled. If it is a member variable in the class, its life cycle is the same as that of the class instance.

3. The memory allocated on the stack starts from calling New or malloc and ends with calling delete or free. Use delete or free if not. This space can be recycled by the system only after the software is running.

Next, let's take a look at what kind of errors we often encounter when using the memory. And what measures should we take.

Memory Errors are very troublesome. The compiler cannot automatically detect these errors, which can be captured only when the program is running. Most of these errors do not have obvious symptoms, but they are often invisible and increase the difficulty of error correction. Sometimes the user finds you angrily, but the program has not encountered any problems. When you leave, the error occurs again.

Common memory errors and their countermeasures are as follows:

1. The memory allocation fails, but it is used.

New programmers often make this mistake because they do not realize that memory allocation will fail. A common solution is to check whether the pointer is NULL before using the memory. If the pointer p is a function parameter, use assert (p! = NULL. If you use malloc or new to apply for memory, you should use if (p = NULL) or if (p! = NULL.

2. Although the memory allocation is successful, it is referenced before initialization.

There are two main causes for this mistake: first, there is no idea of initialization; second, the default initial values of the memory are all zero, resulting in incorrect reference values (such as arrays ).

There is no uniform standard for the default initial values of the memory. Although sometimes it is zero, we prefer to trust it without any trust. Therefore, no matter which method is used to create an array, do not forget to assign the initial value. Even the zero value cannot be omitted, so do not bother.

3. The memory has been allocated successfully and initialized, but the operation has crossed the memory boundary.

For example, when an array is used, the subscript "more than 1" or "less than 1" is often performed. Especially in for loop statements, the number of loops is easy to make a mistake, resulting in array operations out of bounds.

4. I forgot to release the memory, causing memory leakage.

A function containing such errors loses a piece of memory every time it is called. At the beginning, the system had sufficient memory and you could not see the error. Once a program suddenly died, the system prompts: memory is exhausted.

Dynamic Memory application and release must be paired. The usage of malloc and free in the program must be the same, otherwise there must be an error (the same applies to new/delete ).

5. The memory is released, but it is still used.

There are three scenarios:

(1) The object calling relationship in the program is too complex, so it is difficult to figure out whether an object has released the memory. At this time, we should re-design the data structure to fundamentally solve the chaos of Object Management.

(2) The return Statement of the function is incorrect. Be sure not to return the "Pointer" or "Reference" pointing to "stack memory" because the function body is automatically destroyed when it ends.

(3) After the memory is released using free or delete, the pointer is not set to NULL. As a result, a "wild pointer" is generated ".

 

To sum up, we should note that:

1. After applying for memory with malloc or new, check whether the pointer value is NULL immediately. Prevents the use of memory with NULL pointer values.

2. Do not forget to assign initial values to arrays and dynamic memory. Avoid using uninitialized memory as the right value.

3. avoid overrunning the subscript of an array or pointer. Be careful when the "more 1" or "Less 1" Operation occurs.

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

5. After free or delete is used to release the memory, set the pointer to NULL immediately to avoid "wild pointer ".

Here are a few typical examples of errors. Do not make the same mistake:

1. return stack memory pointer

Char * GetString (void)

{

Char * p = "hello world ";

Return p;

}

Char * pGet = GetString ();

This program has no errors during compilation and runs, but you cannot make the returned pGet pointer point to the data you want "hello world ", because the life cycle of the pointer p is within the function GetString, after running the function GetString, the stack space allocated by p is immediately reclaimed by the system. Although pGet points to the memory address originally allocated by p, the address has no content.

2. This is a very frequent error.

Char * pChar = new char;

......

Int;

PChar = &;

......

Delete pChar;

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

This program has two problems. First, pChar = & a; will cause the space allocated by pChar to be unable to be obtained again, just like our lost friend's phone number, we can no longer contact this friend. This causes memory leakage. If the memory leaks more, the system may crash because fewer and fewer resources are available until the system is exhausted. The second problem is that delete pChar will cause an exception because pChar does not point to the dynamically allocated memory, but to the stack space allocated by, stack space cannot be recycled using delete, which causes memory exceptions.

Memory is a fortune, and correct use of wealth is the key, so are people and programming.

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/happyparrot/archive/2004/04/27/21584.aspx

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.