In-depth explanation of precautions for C/C ++ memory management

Source: Internet
Author: User

In the previous article, I will explain C/C ++ memory allocation knowledge instances. The content of this article is reprinted, so it only contains important parts, but does not affect reading.

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 in this chapter is much deeper than that in general textbooks. Readers need to carefully read this chapter to truly understand memory management.

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

7.2 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:
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 ".

[Rule 7-2-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 7-2-2] do not forget to assign initial values to arrays and dynamic memory. Avoid using uninitialized memory as the right value.
[Rule 7-2-3] avoid overrunning the subscript of an array or pointer. Be careful when "more than 1" or "less than 1" is performed.
[Rule 7-2-4] dynamic memory application and release must be paired to prevent memory leakage.
[Rules 7-2-5] After the memory is released with free or delete, the pointer is immediately set to NULL to prevent "wild pointer ".

Let's take a few more instances:

NO.1

Void GetMemory (char * p)
{
P = (char *) malloc (100 );
}
Void Test (void)
{
Char * str = NULL;
GetMemory (str );
Strcpy (str, hello world );
Printf (str );
}

What is the result after running the Test function?

No. 2

Char * GetMemory (void)
{
Char p [] = hello world;
Retrun p;
}
Void Test (void)
{
Char * str = NULL;
Str = GetMemory ();
Printf (str );
}

Problem 1

No. 3


Void GetMemory2 (char ** p, int num)
{
* P = (char *) malloc (num );
}
Void Test (void)
{
Char * str = NULL;
GetMemory (& str, 100 );
Strcpy (str, hello );
Printf (str );
}

Problem 1

No. 4

Void Test (void)
{
Char * str = (char *) malloc (100 );
Strcpy (str, hello );
Free (str );
If (str! = NULL)
{
Strcpy (str, world );
Printf (str );
}
}

Problem 1

Analysis of the above problems:

NO.1: The program first applies for a char pointer str, and points str to NULL (that is, the str contains a NULL address, * the value of str is 0 in NULL ), during the function call process, the following actions are performed: 1. Apply for a char pointer p and 2. copy the str content to p (this is what the system did during the parameter transfer ), 3. 100 spaces are applied for the p pointer, and 4 returns the Test function. finally, the program copies the String hello world to the memory space pointed by str. an error occurred here! The str space is always NULL and there is no actual space. A deep understanding of step 1 of function calling makes it difficult to find the problem! (Suggestion: drawing comprehension)
No. 2: The program first applies for a char pointer str and points str to NULL. when calling a function, the following actions are performed: 1. Apply for an array p [] and assign it to hello world (the size of the array space is 12 ), 2. Returns the array name p to the str pointer (that is, the first address of the array is returned ). so we can print the string "hello world? Of course not! This is because the last step is missing during function calling. that is, after the return array name in step 2, the function call also needs to be performed to release the memory space. when a function is called, it releases the space occupied by all its variables. so the array space is released, that is to say, the content indicated by str will not be sure what it is.
No. 3: The correct answer is that hello can be printed, but the memory is leaked!
No. 4: Apply for space, copy strings, and release space. there are no problems with the first three steps. an error occurred when determining the condition in the if statement, because after a pointer is released, its content is not NULL, but an uncertain value. therefore, if statements cannot be executed. this is also a famous "wild" pointer problem. therefore, after writing a program to release a pointer, we must make it NULL. in this way, the "wild" pointer will be avoided. some people say that the "wild" pointer is terrible and may bring unexpected errors.

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.