Find Memory leakage as quickly as possible

Source: Internet
Author: User

Http://hi.baidu.com/%C0%EE%B6% AB %CF%FE/blog/item/0f1983a170a08989471064aa.html

Memory Management is C ++ProgramEmployee pain. My "memory management revolution" series is trying to discuss more effective memory management methods to prevent (or reduce) memory leaks and reduce the burden on C ++ programmers. Due to busy work, this series is not finished yet and is paused.

In this short article, I 'd like to change my approach to discuss how to find the memory leak as quickly as possible.

Check whether memory leakage exists
We know that if the MFC program detects a memory leak, the system will remind you of the memory leak in the debugging window when you exit the program. For example:

Class cmyapp: Public cwinapp
{
Public:
Bool initapplication ()
{
Int * leak = new int [10];
Return true;
}
};
The memory leakage reports are as follows:

Detected memory leaks!
Dumping objects->
C: \ work \ test. cpp (186): {52} normal block at 0x003c4410, 40 bytes long.
Data: <> CD
Object dump complete.
This is good. The problem is, if we don't like MFC, is there no way? Or do it yourself?

Oh, no. In fact, MFC does not do it on its own. Memory leakage detection is performed by the C Runtime Library of VC ++. That is to say, as long as you are a VC ++ programmer, you can easily detect memory leaks. Let's give an example:

# Include <crtdbg. h>

Inline void enablememleakcheck ()
{
_ Crtsetdbgflag (_ crtdbg_report_flag) | _ crtdbg_leak_check_df );
}

Void main ()
{
Enablememleakcheck ();
Int * leak = new int [10];
}
Run (reminder: Do not press Ctrl + F5 or F5). You will find that the generated Memory leakage report is similar to that of MFC, but the details are different, as shown below:

Detected memory leaks!
Dumping objects->
{52} normal block at 0x003c4410, 40 bytes long.
Data: <> CD
Object dump complete.
Why? See the following.

Locate the memory leakage caused by a sentence
You have found a program memory leakage. The problem is that we need to find the root cause of the leakage.

Generally, we first determine the cause of Memory leakage. In MFC, this is easy. Double-click the text of the Memory Leak report, or press F4 In the debug window. Ide will help you locate the location where you want to apply for the memory block. For the above example, this is the sentence:

Int * leak = new int [10];

This is more or less helpful for analyzing memory leaks. In particular, if this new one corresponds to only one Delete (or you may miss the delete), it will soon be able to identify the crux of the problem.

As we have seen before, when you do not use MFC, the generated Memory leakage report is different from that of MFC, and you immediately find that pressing F4. So what did MFC do?

Actually not. Let's simulate what MFC does. See the following example:

Inline void enablememleakcheck ()
{
_ Crtsetdbgflag (_ crtdbg_report_flag) | _ crtdbg_leak_check_df );
}

# Ifdef _ debug
# Define new (_ normal_block, _ file __, _ line __)
# Endif

Void main ()
{
Enablememleakcheck ();
Int * leak = new int [10];
}

Run this sample again, and you are pleasantly surprised to find that there is no difference between the memory leakage report and the MFC.

Quickly find Memory leakage
It determines the row in which memory leakage occurs. Sometimes it is not enough. In particular, the same new pair should be released in multiple places. In actual projects, the following two situations are typical:

The object is created in the classfactory mode. Many or even all class instances are created by the same new instance. The row of the new output object is not very helpful.

COM object. We know that the COM Object uses reference count to maintain the lifecycle. That is to say, there is only one place for the object new, but there are many places for release. You need to exclude them one by one.
So, how can we quickly locate memory leaks?

A: Yes.

When memory leaks are complex, you can use the following methods to locate memory leaks. This is the most effective method in my opinion in the general memory leakage tracking method.

Let's look back at the memory leakage report generated by crtdbg:

Detected memory leaks!
Dumping objects->
C: \ work \ test. cpp (186): {52} normal block at 0x003c4410, 40 bytes long.
Data: <> CD
Object dump complete.
In addition to the file name and row number of the memory allocation statement that generates the memory leak, we noticed a strange message: {52 }. What does this integer mean?

In fact, it represents the number of Memory Allocation Operations. In this example, {52} indicates that 52nd Memory Allocation Operations have been leaked. You might want to say that I only got new once. How can it be 52nd times? It is easy to understand that other memory application operations are called during the C initialization process. :)

Is it possible that when we let the program run for 52nd Memory Allocation Operations, it will automatically stop and enter the debugging status? Fortunately, crtdbg does provide such a function: long _ crtsetbreakalloc (long nallocid ). We add it:

Inline void enablememleakcheck ()
{
_ Crtsetdbgflag (_ crtdbg_report_flag) | _ crtdbg_leak_check_df );
}

# Ifdef _ debug
# Define new (_ normal_block, _ file __, _ line __)
# Endif

Void main ()
{
Enablememleakcheck ();
_ Crtsetbreakalloc (52 );
Int * leak = new int [10];
}
You find that when the program runs to int * leak = new int [10], it automatically stops and enters the debugging status. By taking a closer look, you can find that the information you obtain in this way is far more valuable than obtaining the file name and row number when the program exits. Because the report exposes the file name and row number, you only obtain static information. However, _ crtsetbreakalloc restores the entire site, you can analyze the function call stack (I find that many people are not used to reading the function call stack. If you are in this situation, I strongly recommend that you complete this course, because it is too important) and other online debugging skills to analyze the cause of Memory leakage. Generally, this analysis method can locate the cause within five minutes.

Of course, _ crtsetbreakalloc requires that the execution process of your program be recoverable (the memory allocation sequence of multiple execution processes will not change ). This assumption is true in most cases. However, in the case of multithreading, this is sometimes difficult to guarantee.

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/zdl1016/archive/2009/03/30/4035901.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.