_ Crtdumpmemoryleaks () function to detect memory leakage

Source: Internet
Author: User

_ Crtdumpmemoryleaks ()

Crtdumpmemoryleaks () indicates the current Memory leakage.
Note that it is "current", that is, when it is executed,
Memory leakage is reported for all objects not destroyed.

Therefore, try to run this statement at the end of the program.

It reflects the Leak detected.
Generally, it is accurate in MFC and _ crtdumpmemoryleaks is called in initinstance.

 

C ++ memory allocation and release are all controlled by the user code. The flexible mechanism is like Pandora's box, which gives programmers a wider play.

Space also produces memory leaks from generation to generation. For beginners, the most common mistake is to release a new object and forget to release it. For small applications, a little memory space is nothing. However, when the memory leakage occurs on a platform program that requires 24 hours of operation, the system's available memory will be quickly reduced, and system resources will be exhausted, resulting in system crash.

Therefore, learning how to prevent and check memory leaks is a must-have capability for qualified C ++ programmers. However, a memory leak occurs only when the program runs and meets certain conditions. It is difficult to directly identify the cause of the leak from the code, and once the memory leak occurs in a multi-thread program, from a large amount of code, it is a nightmare to find out the cause of the leak, whether it is a newcomer or veteran.

This article introduces a method to check memory leakage in vs2003 for reference by new Veterans. Some changes need to be made in vc6. For details, refer to relevant information.

Check Policy Analysis

First, assume that we need to detect the memory leakage of a 24-hour platform program, and we cannot determine the specific memory leakage speed, however, we can determine that the amount of memory leaked by the Program within a certain period of time (such as 10 minutes) is close to that set to L (EAK ).

Consider the memory a (lloc) newly applied by the program within the 10-minute running time. This part of memory actually contains the application for normal program running, the normal memory block N (ormal) and the leaked memory l, that is, a = N + L, which will be released in the subsequent running.

In the subsequent operation, due to the continuous application and release of N parts, the total amount of this part is basically unchanged, and l part is only applied for but not released, the total memory used will increase.

Put this result on the running timeline. Now we observe that the program is running for 20 minutes. We assume that the memory leakage speed is DL/10 minutes. The timeline is as follows:

 

----------------|--------------------|-------------------|----------------------------              Tn-2 Tn-1 Tn

If the three-point interval is 10 minutes, we draw a conclusion:

Total memory allocation at TN: An = N + DL * n, n indicates normal memory allocation, and DL * n indicates the total memory leakage, the total memory of the Tn-1 point is an-1 = N + DL * (n-1 ). Note: We will not consider the amount of memory released here, but the amount of memory added. Therefore, it is obvious that the memory leakage per unit time is DL = an-1.

Code implementation for generating memory dump files

To complete the above policy, we first need to be able to track the allocation and release of memory blocks, and save the allocation to the file at runtime for comparative analysis, fortunately, M $ has provided us with a complete set of methods to facilitate memory tracking. The specific implementation steps are as follows:

Contains the library required for memory Tracing

Add the following code to stdafx. H. Note that the macro _ crtdbg_map_alloc must be defined; otherwise, the location of the memory block code will be missing in the subsequent dump file.

 

# Ifdef _ debug // For memory leak check # DEFINE _ crtdbg_map_alloc // until the generated memory dump contains the specific code for memory block allocation # include # endif

Enable memory Tracing

After completing the preceding steps, you can add the following code at the application startup to start the memory tracing. After the startup, the program will automatically detect the memory allocation and release and allow the result output.

 

//enable leak check              _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG);

Direct the result output to the dump file

By default, the dump content of Memory leakage is output to the debug output window of Vs, but the service program cannot track Memory leakage in the debug mode of, therefore, the dump content output must be transferred to the dump file. Add the following parts to the program:

 

Handle hlogfile; // declare the log file handle hlogfile = createfile (". /log/memleak. log ", generic_write, file_share_write | file_share_read, null, create_always, file_attribute_normal, null); // create the log file _ crtsetreportmode (_ crt_warn, _ crtdbg_mode_file ); // output warn-level content to the file (note that the dump report level is warning) _ crtsetreportfile (_ crt_warn, hlogfile ); // set the log file as the alarm output file

Save memory dump

After completing the above settings, we can add the following code in the program and output the memory dump to the specified dump file:

 

_ Crtmemstate S1, S2, S3; // defines three temporary memory statuses ...... _ crtdumpmemoryleaks (); // dump the allocated but not released memory from the start of the program to the current time point, that is, the preceding an // is not necessary, add information _ crtmemcheckpoint (& S2); If (_ crtmemdifference (& S3, & S1, & S2) {_ crtmemdumpstatistics (& S3 ); // dump memory block changes between neighboring time points // For next compare _ crtmemcheckpoint (& S1);} time_t now = time (0 ); struct TM * nowtime = localtime (& now); _ rpt4 (_ crt_warn, "% 02d % 02d: % 02d: % 02d snapshot dump. /n ", nowtime-> tm_mday, nowtime-> tm_hour, nowtime-> tm_min, nowtime-> tm_sec); // output the dump time

It is recommended that the above Code be periodically triggered by the timer in a function, or manually generated by snapshot to generate memory dump for an equal period of time.

Dump File Content example:

 

Detected memory leaks!              Dumping objects ->              {20575884} normal block at 0x05C4C490, 87 bytes long.              Data: 02 00 1D 90 84 9F A6 89 00 00 00 00 00 00 00 00              ...              d:/xxxxx/xxxworker.cpp(903) : {20575705} normal block at 0x05D3EF90, 256 bytes long.              Data: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00              ...              Object dump complete.              0 bytes in 0 Free Blocks.              215968 bytes in 876 Normal Blocks.              0 bytes in 0 CRT Blocks.              0 bytes in 0 Ignore Blocks.              0 bytes in 0 Client Blocks.              Largest number used: 220044 bytes.              Total allocations: 7838322 bytes.              10 16:29:14 snapshot dump.

The red part above is the memory block location allocated in the user code but not released.

Parse dump files

We have obtained the memory dump at various time points through the dump file. According to the previous analysis policy, we only need to allocate the memory blocks of the nth dump to, compared with the memory block allocation of the n-1 dump, the location where the memory leakage occurs is located. Because dump files are generally of huge capacity, * manual comparison is almost impossible. Therefore, we only need to introduce the comparison ideas. You need to make your own gadgets for processing.

1. Extract the dump files D1 and D2 at two adjacent time points, and set D1 to dump before D2.

2. Extract the memory blocks allocated by the user code in the dump file (that is, the memory blocks with a clear code position and a normal block) respectively based on the memory block ID (such as "D: /XXXXX/xxxworker. CPP (903): {20575705} "red part) is saved in list L1 and L2

3. traverse the list L2 and record the memory blocks whose memory block IDs have not exceeded in L1. These memory blocks are potentially leaked memory blocks.

4. Based on the result of 3, calculate the number of memory blocks leaked by code in each area based on the memory allocation code location, and sort the code in descending order. The more code is allocated, the more likely the memory leakage will be.

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.