High-quality C++/C Programming Guide-7th Chapter-Memory Management (1)

Source: Internet
Author: User

Welcome to the memory of this mined area. The great Bill Gates has made a slip of the tongue: 640K ought to is enough for everybody

-bill Gates 1981

Programmers often write memory management programs that are often scary. If you do not want to accidents, the only solution is to find all the hidden mines and eliminate them, hiding can not hide. The content of this chapter is much deeper than the general textbooks, readers need to read carefully, so that really proficient in memory management.

7.1 Memory allocation method
There are three ways to allocate memory:

(1) Distribution from the static storage area. The memory is allocated when the program is compiled, and exists throughout the running of the program. such as global variables, static variables.

(2) created on the stack. When the function is executed, the storage units of local variables within the function can be created on the stack, and the storage units are automatically freed when the function is finished. Stack memory allocation operations are placed within the processor's instruction set, which is highly efficient, but allocates a limited amount of memory.

(3) Allocation from the heap, also known as dynamic memory allocation. The program uses malloc or new to request any amount of memory at run time, and the programmer is responsible for releasing the memory with free or delete. The lifetime of dynamic memory is determined by us and is very flexible to use, but the problem is the most.

7.2 Common memory errors and Countermeasures
A memory error is a very troublesome thing to do. The compiler cannot automatically discover these errors, which are usually captured when the program is running. Most of these errors do not have obvious symptoms, the hidden, increase the difficulty of error. Sometimes the user angrily to find you, the program has not happened any problems, you go, the wrong again attack.

Common memory errors and their countermeasures are as follows:

U memory allocation was unsuccessful, but it was used.

Novice programmers often make this mistake because they are unaware that memory allocations will be unsuccessful. A common workaround is to check whether the pointer is null before using memory. If the pointer p is a function argument, check it with assert (P!=null) at the entrance to the function. If you are using malloc or new to request memory, you should use if (p==null) or if (P!=null) for error proofing.

U memory allocation is successful, but it is referenced before it has been initialized.

There are two main causes of this error: one is the idea that there is no initialization; the second is to mistakenly assume that the default initial value of the memory is all zero, resulting in a reference to an initial error (for example, an array).

There is no uniform standard for what the default initial value of memory is, and although sometimes it is zero, we would rather believe that it has. So no matter how you create an array, do not forget to assign an initial value, even if it is assigned 0 values can not be omitted, do not bother.

U memory allocation was successful and initialized, but the operation crossed the bounds of memory.

For example, when using an array, the subscript "more 1" or "less 1" is often taken place. Especially in the For Loop statement, the number of loops is easily mistaken, causing the array operation to cross over.

U forgot to release memory, causing memory leak.

A function that contains this error loses a piece of memory every time it is called. The system has plenty of memory at first, and you can't see the error. A program suddenly dies, the system prompts: memory exhaustion.

Dynamic memory application and release must be paired, in the program malloc and free use of the same number of times must be the same, otherwise there must be errors (new/delete).

U frees up memory but continues to use it.

There are three kinds of situations:

(1) The object invocation in the program is too complex, it is difficult to find out whether an object has released memory, at this time should redesign the data structure, fundamentally solve the object management confusion.

(2) The return statement of the function is incorrectly written, and be careful not to go back to "stack memory" pointer or "reference" because the memory is automatically destroyed at the end of the function body.

(3) When memory is freed with free or delete, the pointer is not set to null. Causes the "wild pointer" to be generated.

L "rule 7-2-1" after using malloc or new to request memory, you should immediately check that the pointer value is NULL. Prevents the use of memory with a pointer value of NULL.

L "rule 7-2-2" do not forget to assign an initial value to an array and dynamic memory. Prevents unused memory from being initialized as a right value.

L "Rule 7-2-3" avoids the scaling of arrays or pointers, especially beware of "more 1" or "less 1" operations.

L "rule 7-2-4" dynamic memory requests and releases must be paired to prevent memory leaks.

L "Rule 7-2-5" frees memory with free or delete, and immediately sets the pointer to NULL to prevent "wild pointers" from being generated.

7.3 Comparison of pointers and arrays
In c++/c programs, pointers and arrays can be substituted for each other in many places, giving people an illusion that they are equivalent.

Arrays are either created in the static store (such as global arrays) or created on the stack. The array name corresponds to (rather than points to) a piece of memory, and its address and capacity remain unchanged for the duration of the lifetime, and only the contents of the array can be changed.

Pointers can be pointed at any time to any type of memory block, which is characterized by "variable", so we often use pointers to manipulate dynamic memory. Pointers are far more flexible than arrays, but they are also more dangerous.

The following is an example of a string that compares the attributes of a pointer to an array.

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.