Common dynamic memory errors-Memory leakage, dynamic memory-Leakage

Source: Internet
Author: User

Common dynamic memory errors-Memory leakage, dynamic memory-Leakage

Common dynamic memory errors

The compiler cannot automatically detect dynamic memory errors. dynamic memory errors can only be captured when the program is running, and the cause of errors is not easy to find. errors are not easy to capture, making it difficult to correct errors.



1. The dynamic memory allocation fails, but the operation continues.
Insufficient memory may cause dynamic memory allocation to fail. Therefore, you must check whether the returned address is NULL After allocating dynamic memory with the new request.
For example, if (p = NULL) or if (p! = NULL) Check. Do not operate on dynamic memory before checking.


2. Read the dynamic memory space before Initialization
The C ++ standard does not specify the default value of the dynamic memory space. The program cannot predict the default value. Therefore, uninitialized dynamic memory space may hold an uncertain value.
Therefore, when requesting to allocate dynamic memory space, initialize the dynamic memory space and try not to use the default system value.


3. dynamic memory space used out of bounds
Although the pointer is very powerful, it is easy to point to the wrong place. When the pointer points to an incorrect data type, the pointer operation will fail.
Especially when the pointer points to an array, it is easy to cross-border and cause errors.


4. Memory leakage
Memory leakage is a serious dynamic memory error. After a program runs for a long time, the memory may be exhausted, and the running speed may slow down or even the system may crash.
For example, if new and delete are not paired, the new space may not be deleted.
After applying for the allocated memory space using the new operator, remember to use delete to release it, and the new format must correspond to delete.


5. continue to use the released dynamic memory space
After the delete operation, the value of the corresponding pointer variable is not changed, and it still points to the original dynamic memory space, but the content of the original dynamic memory space is meaningless.

Therefore, after executing the delete operation, you usually need to set the value of the pointer variable to NULL to avoid misoperation or invalid operations on the memory space.


The following describes the memory leakage:


Memory leakage

The program fails to release memory that is no longer in use due to negligence or errors.
Memory leakage does not mean that the internal memory disappears physically, but that after the application allocates a certain segment of memory, the memory is wasted due to design errors and the loss of control over this segment of memory.


The following are examples:

1. Next, a first applies for an int-type dynamic memory space with an initial value of 12. Next, a applies for an int-type space with an initial value of 34,
The first storage of 12 will not be released, and the storage of 12 will not be released or used, resulting in Memory leakage.

# Include <iostream> using namespace std; int main () {int * a = new int (12); cout <* a <endl; // delete a is required; a = new int (34); cout <* a <endl; delete a; system ("pause"); return 0 ;}
2. The following function creates a char-type array in the dynamic memory when called, and generates a char-type pointer variable pChar in bytes, pointing to the array with pChar.
When the f call ends, pChar will automatically disappear because it is located in the region and is a local variable;
The string array in the dynamic memory space with a length of 100 still exists and is not released.
Therefore, after exiting F (), the memory will leak, and each call will cause a new leak.
void F(void){char *pChar=new char [100];//do something}
The best practice is:

void F(void){char *pChar=new char [100];//do somethingdelete []pChar;}

3. What are the following problems?

// F returns a pointer pointing to a dynamically allocated object int * F (T arg) {return new int [arg]; // the caller is responsible for releasing this memory}

The function that returns the pointer to the dynamic memory adds an extra burden to its callers-the caller must remember to release the memory.


4. delete only provides limited protection

See the following example:

After the delete operation, the value of the corresponding pointer variable is not changed, and it still points to the original dynamic memory space, but the content of the original dynamic memory space is meaningless.
Therefore, after executing the delete operation, you usually need to set the value of the pointer variable to NULL to avoid misoperation or invalid operations on the memory space.

However,

int *p=new int (42);auto q=p;delete p;p=NULL;

P and q point to the same dynamically allocated object. We delete this memory and Set p to NULL, indicating that it no longer points to any object. However, resetting p has no effect on q. q becomes invalid when we release the memory pointed to by p (which is also pointed to by q. In the actual system, it is difficult to find all pointers pointing to the same memory.


How can we get a memory leak error?

If the requested memory is not released, the memory is leaked.

For example.
Void GetMemory (int len)
{
Int * p = new int [len];
}

P applied for memory, but the function returned. The first address without a pointer is passed out and cannot be released.

Handle Memory leakage in vc

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

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.