Entering the minefield in C ++-C ++ memory management details

Source: Internet
Author: User

The great Bill Gates once said:

640 K ought to be enough for everybody-Bill Gates 1981

Programmers often write memory management programs, so they are always worried. If you don't want to touch the mines, the only solution is to discover all the hidden mines and exclude them. The content of this article is much deeper than that of general textbooks. Readers must carefully read this article to truly understand memory management.

  1. Memory Allocation Method

There are three memory allocation methods:

(1) distribution 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.

  2. Common memory errors and Countermeasures

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:

* If the memory allocation is unsuccessful, 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)

Check. If you use malloc or new to apply for memory, you should use if (p = NULL) or if (p! = NULL.

* 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.

* The memory allocation is successful and initialized, but the operation is beyond 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.

* 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 ).

* The memory is released but it is used again.
 
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 ".

[Rule 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.

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

Rule 3: avoid overrunning the subscript of an array or pointer. Be careful when "more than 1" or "less than 1" is performed.

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

[Rule 5] after the memory is released with free or delete, the pointer is immediately set to NULL to avoid "wild pointer ".

  3. Comparison of pointers and Arrays

In C ++/C Programs, pointers and arrays can be replaced with each other in many places, which leads to the illusion that the two are equivalent.

An array is either created in a static storage area (such as a global array) or on a stack. The array name corresponds to (rather than pointing to) a piece of memory, and its address and capacity remain unchanged during the lifetime, only the content of the array can be changed.

A pointer can point to any type of memory block at any time, and its feature is "variable". Therefore, we often use pointers to operate dynamic memory. Pointers are far more flexible than arrays, but they are more dangerous.

The following uses a string as an example to compare the features of pointers and arrays.

3.1 modify content

In the example 3-1, the size of character array a is 6 characters, and its content is hello. The content of a can be changed, for example, a [0] = 'x '. The pointer p points to the constant string "world" (in the static storage area with the content of world). The content of the constant string cannot be modified. In terms of syntax, the compiler does not think that the statement p [0] = 'X' is inappropriate, but this statement attempts to modify the content of the constant string and causes a running error.

Char a [] = "hello ";
A [0] = 'X ';
Cout <a <endl;
Char * p = "world"; // note that p points to a constant string
P [0] = 'X'; // the compiler cannot find this error.
Cout <p <endl;
Example 3.1 modify the array and pointer content

3.2 content replication and Comparison

The array name cannot be directly copied or compared. In Example 7-3-2, if you want to copy the content of array a to array B, you cannot use statement B = a. Otherwise, a compilation error is generated. Use the standard library function strcpy for replication. Similarly, if the content of B and a is the same, it cannot be determined by if (B = a). The standard library function strcmp should be used for comparison.

Statement p = a does not copy the content of a, but assigns the address of a to p. To copy the content of a, use the library function malloc as p to apply for a memory with a capacity of strlen (a) + 1 characters, and then use strcpy to copy strings. Similarly, the statement if (p = a) compares not the content but the address, and should be compared using the database function strcmp.

// Array...
Char a [] = "hello ";
Char B [10];
Strcpy (B, a); // B = a cannot be used;
If (strcmp (B, a) = 0) // if (B = a) cannot be used)
...
// Pointer...
Int len = strlen ();
Char * p = (char *) malloc (sizeof (char) * (len + 1 ));
Strcpy (p, a); // do not use p =;
If (strcmp (p, a) = 0) // do not use if (p =)
...
Example 3.2 copying and comparing the array and pointer content

3.3 computing memory capacity

The sizeof operator can be used to calculate the array capacity (number of bytes ). In Example 7-3-3 (a), the value of sizeof (a) is 12 (don't forget ''). The pointer p points to a, but the value of sizeof (p) is 4. This is because sizeof (p) obtains the number of bytes of a pointer variable, which is equivalent to sizeof (char *) rather than the memory capacity referred to by p. C ++/C language cannot know the memory capacity referred to by the pointer unless you remember it when applying for memory.

Note: When an array is passed as a function parameter, the array will automatically degrade to a pointer of the same type. In Example 7-3-3 (B), sizeof (a) is always equal to sizeof (char *) regardless of the size of array *).

Char a [] = "hello world ";
Char * p =;
Cout <sizeof (a) <endl; // 12 bytes
Cout <sizeof (p) <endl; // 4 bytes
Example 3.3 (a) calculates the memory capacity of arrays and pointers

Void Func (char a [1, 100])
{
Cout <sizeof (a) <endl; // 4 bytes instead of 100 bytes
}
Example 3.3 (B) the array degrades to a pointer


4. How does the pointer Parameter Pass the memory?

If the function parameter is a pointer, do not expect this pointer to apply for dynamic memory. In Example 7-4-1, the GetMemory (str, 200) Statement of the Test function does not enable str to obtain the expected memory. str is still NULL. Why?

Void GetMemory (char * p, int num)
{
P = (char *) malloc (sizeof (char) * num );
}
Void Test (void)
{
Char * str = NULL;
GetMemory (str, 100); // str is still NULL
Strcpy (str, "hello"); // running error
}
Example 4.1 try to apply for dynamic memory with pointer Parameters

The fault lies in the GetMemory function. The compiler always needs to make a temporary copy for each parameter of the function. The copy of the pointer parameter p is _ p, and the compiler makes _ p = p. If the program in the function body modifies the content of _ p, the content of parameter p is modified accordingly. This is why pointers can be used as output parameters. In this example, _ p applied for a new memory, but changed the memory address indicated by _ p, but p was not changed at all. Therefore, the GetMemory function cannot output anything. In fact, each execution of GetMemory will leak a piece of memory, because the memory is not released with free.

If you have to use the pointer parameter to request memory, you should use "pointer to Pointer" instead. See example 4.2.

Void GetMemory2 (char ** p, int num)
{
* P = (char *) malloc (sizeof (char) * num );
}
Void Test2 (void)
{
Char * str = NULL;
GetMemory2 (& str, 100); // note that the parameter is & str, not str
Strcpy (str, "hello ");
Cout <str <endl;
Free (str );
}
Example 4.2 apply for dynamic memory with a pointer pointing to the pointer

Because the concept of "pointer to Pointer" is not easy to understand, we can use function return values to transmit dynamic memory. This method is simpler. See example 4.3.

char *GetMemory3(int num)
{
 char *p = (char *)malloc(sizeof(char) * num);
 return p;
}
void Test3(void)
{
 char *str = NULL;
 str = GetMemory3(100);
 strcpy(str, "hello");
 cout<< str << endl;
 free(str);
}
Example 4.3 use function return values to transmit dynamic memory

Although it is easy to use the function return value to pass dynamic memory, some people often use the return statement wrong. Here, we do not use the return statement to return the pointer to the "stack memory" because

Related Article

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.