Detect and isolate memory leaks in VisualC ++

xiaoxiao2021-03-06  64

Detecting and isolating memory leaks in Visualc [Collection] The ability to dynamically assign and release memory is one of the important features of the C / C program language. The Visualc Debugger and CRT libraries offer a range of tools for detecting and identifying memory leaks.

Set memory leak detection

The basic tool for detecting memory leaks is the debugger and CRT debug heap function. In order to use the debug heap function, you must contain the following description in your program:

#define _crtdbg_map_alloc # include #include

The order of the above declaration must be guaranteed, and if the order is changed, it may not work properly. _malloc_dbg and _free_dbg will appear in the debug version in the Debug version, which can track the allocation and release of memory. But this will only happen in the Debug version (when #define _debug), and the Release version still uses the standard Malloc and Free feature.

#define _crtdbg_map_alloc Represents the corresponding debug version using the CRT heap function. This definition is not necessary, but without it, the memory leak report is only available at information.

Once you have added the current statement, you can report the memory leak information by adding the following code to the program:

_CRTDUMPMEMORYLEAKS ();

When running the program in the debug mode, the DEBUG tab at the Output window will display the information of the memory leak, for example:

Detected memory Leaks! DUMPING OBJECTS -> C: / Program Files / Visual Studio / MyProjects / LeakTest / LeakTest.cpp (20): {18} Normal Block AT 0x00780E80, 64 BYTES Long.Data: <> CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD OBJECT DUMP COMPLETE.

If there is no #define _crtdbg_map_alloc, the memory leak report will be like this:

Detected memory Leaks! DUMPING OBJECTS -> {18} Normal Block AT 0x00780E80, 64 BYTES Long.Data: <> CD CD CD CD CD CD CD CD CD CD CD CD CD CD Object Dump Complete.

This shows that _CRTDBG_MAP_ALLOC is defined, _CRTDUMPMEMORYLE AKS provides more useful information.

If no _crtdbg_map_alloc, the memory leak report is shown below:

Memory Allocation Numerical (Praggies) Module (Normal, Client or CRT) Positioning the memory in the 16-in-format format, the first sixteen-seated content of the byte coupon module (can also use hex system)

If _CRTDBG_MAP_ALLOC is defined, the reported content also includes files that appear allocated. The numbers in the parentheses after the file name are the number of rows within the file.

At this point, double-click the output line containing the row value and the file name, or select the output line and press F4:

C: / Program Files / Visual Studio / MyProjects / LeakTest / LeakTest.cpp (20): {18} Normal Block AT 0x00780E80, 64 BYTES Long.

The edit window will jump to the line code of the split memory in the file, the line number in LeakTest.cpp is 20. Use _crtsetdbgflag

If your program only exits one place, it is very easy to select the location of the call _CRTDumpMemoryLeaks. However, if your program may exit multiple positions in the program? If you don't want to call _crtdumpMemoryLeaks at each possible exit, then you can include the following calls at your program:

_CRTSETDBGFLAG (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

When the program exits, _CRTDUMPMEMORYLEAKS will be called automatically, and _CRTDBG_ALLOC_MEM_DF and _CRTDBG_LEAK_CHECK_DF) will be automatically called.

Translation memory module Type

The memory leak report is divided into ordinary blocks, client blocks, and CRT blocks in the memory leak report. In fact, you only need to pay attention to normal blocks and client block types.

Normal Block: The memory allocated by your program.

CLIENT Block: is a special memory block, which is an object used by the MFC. When the program exits, the sect of the object is not called. The MFC New operator can be used to create normal blocks and client blocks.

CRT Block: The memory block allocated by C Runtime Library is used by C Runtime Library. The CRT library manages these memory allocation and release, usually you don't find CRT memory leaks in the memory leak report, unless the program has a serious error (such as CRT library collapse).

Below these two types of memory blocks do not appear in the memory leak report:

Free Block: The memory already released (free).

Ignore Block: It is a programmer explicitly declared memory blocks that do not appear in the memory leak report.

Set CRT Report Style

Usually _CRTDUMPMEMORYLEAKS () will be DUMP memory leakage information to the Debug field of the Output window. You can use _CRTSetReportMode () to reset the output to another. For more detailed how to use _CRTSetReportMode (), please check the MSDN.

Set a breakpoint at the number of memory allocations

The file names and line numbers in the memory leak report can tell the code location of the split memory, but the light is to completely understand the reason for the leak, sometimes it is not enough. Because a program is running, the code allocated allocation memory will be called many times, but may be the release of the discharge after a certain call. In order to determine that those memory is not released, you must not only know that the inner existence of leaks is allocated, but also know the conditions generated by leakage. For you, the helpful information is the memory allocation number - the value that appears in the pair of parcels after the file name and the line number.

For example, in the output information below, "18" is a memory distribution number, meaning the leak memory is the 18th memory block allocated in your program:

Detected memory Leaks! DUMPING OBJECTS -> C: / Program Files / Visual Studio / MyProjects / LeakTest / LeakTest.cpp (20): {18} Normal Block AT 0x00780E80, 64 BYTES Long.Data: <> CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD OBJECT DUMP COMPLETE.

The CRT library is counting all memory modules allocated during the program, including CRT own memory or other modules, such as MFC or the like. Therefore, an object with the distribution number N is the nth object assigned in your program, but does not mean the Nth object assigned by the code (in most cases, it will not be.) In this case, you can set a breakpoint using the allocation number where the memory is allocated. In order to set such an endpoint, you can set a location breakpoint at the beginning of your program. When your program is at that point break, you can set a location breakpoint from the QuickWatch dialog or Watch window.

For example, in the Watch window, type the following expression at the NAME field:

_CRTBREAKALLOC

If you are using the multi-threaded version of CRT library Dynamic-Link Library (DLL), you must contain context operators, like this:

{, MSVCRTD.DLL} _CRTBreakalloc

Now press the return key, the debugger finds this value and places the result in the Value column. If you have not set any memory allocation breakpoints during the memory allocation, then this value is -1. Use the allocated value of the memory allocation you want to interrupt, replace the value in the Value table - for example, 18.

Continue to debug after the memory allocation breakpoint is set. At this time, be careful when running the program, to ensure that the order in which the memory block allocation is not changed. When your program is interrupted in the memory allocation point, you can view the Call Stack window and other debug information to analyze the reason for the leak. You can still continue from that point, so that what happened, while determining why memory is not released (set up a memory allocation breakpoint is very helpful).

Although it is usually easier to set up memory allocation breaks in the debugger, if you like, you can set them in your code. In order to set a memory allocation breakpoint in your code, you can add such a line (for the eighteenth memory allocation):

_CRTBREAKALLOC = 18;

You can also use the _CRTSetBreakalloc function with the same effect:

_CRTSETBREAKALLOC (18);

Compare memory status

Another way to locate memory leaks is to make snapshots on the memory status of the application in a key point. The CRT library provides a structural type_CrtMemState. You can use it to store a snapshot of memory status:

_CRTMEMSTATE S1, S2, S3;

In order to snapakap up in a specific point, a _crtMemState structure to the He _CRTMEMCHECKPOINT function can be passed. This function fills this structure with a snapshot of the memory status at the time:

_CRTMEMCHECKPOINT (& S1);

You can pass this structure to the _crtmemdumpstatistics function to the contents of the Dump _CRTMemState structure:

_CRTMEMDUMPSTATISTICS (& S1);

This function prints a pile of memory allocation information similar to the following:

0 BYtes in 0 Normal Blocks.071 Bytes in 16 CRT Blocks.0 Bytes in 0 Client Blocks.Largest Number Used: 3071 bytes.total Allocations: 3764 bytes.

In order to determine if a memory leak appears in a section code, you can make a snapshot of the memory status before and after this section, then compare two states with _CRTMEMDIFCERENCE:

_CRTMEMCHECKPOINT (& S1); // Memory Allocations Take Place Here ...

_CRTMemcheckPoint (& S2);

IF (_CRTMEMDIFERENCE (& S3, & S1, & S2)) _CRTMEMDUMPSTATICS (& S3);

From the name, _crtmemdifference is used to compare two memory status (the two parameters of the last side), and return the results of the status difference (first parameter). The _CRTMemCheckPoint calls and enables _CRTMEMDIFFERENCE to compare the results for the detection of memory leaks. If a leak is detected, you can use the _CRTMemCheckPoint call to split your program and use the binary search technique to locate the leak.

转载请注明原文地址:https://www.9cbs.com/read-85157.html

New Post(0)