How to enable memory leak detection in VC + + 6.0? __c++

Source: Internet
Author: User
VC + + IDE default state is not enabled memory leak detection mechanism, that is, even if a piece of code has a memory leak, debugging session Output window of the Debug page does not output information about memory leaks. You must set up two basic agencies to enable the memory leak detection mechanism.

One is to use the debug heap function:

#define _crtdbg_map_alloc
#include <stdlib.h>
#include <crtdbg.h>

Note: #include the order of the statements. If you change this order, the function you are using may not work correctly.

By including the Crtdbg.h header file, you can map the malloc and free functions to their debug versions _malloc_dbg and _free_dbg, which track memory allocation and deallocation. This mapping is only valid in debug (debug) versions (that is, to define _DEBUG). Distribution (release) uses the normal malloc and free functions.
The #define statement maps the underlying version of the CRT heap function to the corresponding debug version. The statement is not required, but if there is no such statement, the information about the memory leak will not be complete.

The second is to add the following statement to output memory leak information where memory leaks are needed:

_CrtDumpMemoryLeaks ();

When you run the program under the debugger, _CrtDumpMemoryLeaks displays the memory leak information in the Debug page of the Output window. Like what:

Detected memory leaks!
Dumping Objects->
C:/temp/memleak/memleak.cpp: {{} normal block at 0x00441ba0, 2 bytes long.
Data: <AB> 41 42
C:/Program Files/microsoft Visual Studio/vc98/include/crtdbg.h (552): {} normal block at 0x00441bd0, bytes long.
Data: < C > CD CD CD CD CD CDs CD CD
C:/Program Files/microsoft Visual Studio/vc98/include/crtdbg.h (552): {n} normal block at 0x00441c20, bytes long.
Data: < C > 08 02 43 00 16 00 00 00 00 00 00 00 00 00 00 00
Object dump complete.

If you do not use the #define _CRTDBG_MAP_ALLOC statement, the output of the memory leak is this:

Detected memory leaks!
Dumping Objects->
{{} normal block at 0x00441ba0, 2 bytes long.
Data: <AB> 41 42
{{} normal block at 0x00441bd0, bytes long.
Data: < C > CD CD CD CD CD CDs CD CD
{{} normal block at 0x00441c20, bytes long.
Data: < C > C0 01 43 00 16 00 00 00 00 00 00 00 00 00 00 00
Object dump complete.

Depending on the output information, you cannot know which source program file has a memory leak. Now let's look at the format of the output information. The first and second lines have nothing to say, starting with the third line:

{XX}: The number in brackets is the memory allocation sequence number, this example is {45},{44},{43};
Block: The type of memory blocks, commonly used in three kinds: normal (normal), clients (client) or CRT (runtime); In this example, normal block;
Memory location in hexadecimal format, such as at 0x00441ba0;
The size of the memory block expressed in bytes, such as: bytes long;
The first 16 bytes of content (also in hexadecimal format), such as: Data: <AB> 41 42, etc.;

Careful observation is not difficult to find, if the definition of _crtdbg_map_alloc, then the memory allocation sequence will also show the name of the file in which to allocate leaked memory, as well as the number of parentheses after the filename indicates the line number of the leak, such as:

C:/temp/memleak/memleak.cpp (15)

Double-click the output line that contains the file name in the Output window to jump to the line of code where the source program file allocates the memory (or select the row and press F4 to do the same), so that we can easily locate where the memory leak occurred, so _crtdbg_map_alloc The role is obvious.

using _CrtSetDbgFlag

If the program has only one exit, then the location of the call _CrtDumpMemoryLeaks is easy to choose. But what if the program might quit in more than one place? It is certainly undesirable to call _CrtDumpMemoryLeaks at every possible exit, then you can include the following call at the beginning of the program:

_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _crtdbg_leak_check_df);

This statement will automatically invoke _CrtDumpMemoryLeaks regardless of where the program exits. Note: You must also set two bit domain flags: _CRTDBG_ALLOC_MEM_DF and _CRTDBG_LEAK_CHECK_DF.

set up CRT reporting mode

By default, _CrtDumpMemoryLeaks dumps the memory leak information into the Debug page of the Output window, and if you want to redirect the output to another place, you can use _CrtSetReportMode to reset it. If you use a library, it may direct the output to another location. At this point, you can use the following statement to set the output location back to the print window:

_CrtSetReportMode (_crt_error, _crtdbg_mode_debug);

For more information about using _CrtSetReportMode, refer to the MSDN Library's description of _CrtSetReportMode.

Interpreting memory block types

As already mentioned, the memory leak report divides each piece of leaked memory into normal (normal block), client-side block, and CRT block. In fact, what needs attention and attention is normal and client, that is, common blocks and block of clients.

Normal block (plain blocks): This is the memory allocated by your program.
Client block (Customer blocks): This is a special type of memory block that is used specifically for objects in the MFC program that require destructors. The MFC new operator, depending on the situation, can either establish a common block for the object being created or create a customer block for it.
· CRT block (CRT blocks): A block of memory allocated by the C RunTime Library for its own use. The CRT library manages the allocation and release of these allocations on its own, and we typically do not find a CRT memory leak in the memory leak report unless there is a serious error in the program (such as a CRT library crash).

In addition to the above types, there are two types of memory blocks that do not appear in the Memory leak report:

Free Block (idle block): A chunk of memory that has been freed (free).
gnore block (Ignore blocks): This is the memory block that the programmer explicitly declares not to appear in the memory leak report.

How to set a breakpoint at the memory allocation ordinal.


In the memory leak report, the file name and line number can tell the location of the code where the leaked memory is allocated, but it is not sufficient to rely solely on this information to understand the full cause of the leak. Because a program is running, a section of code that allocates memory may be invoked many times, and a memory leak can occur if the memory is not freed after one call. In order to determine which memory is not released, not only to know where the leaking memory is allocated, but also to know the conditions of the leak. The memory allocation sequence number is particularly useful-the number is the one in the bracket after the filename and line number.
For example, in the output information of this example code, "45" is the memory allocation sequence number, meaning that the leaking memory is the 45th memory block allocated in your program:

Detected memory leaks!
Dumping Objects->
C:/temp/memleak/memleak.cpp: {{} normal block at 0x00441ba0, 2 bytes long.
Data: <AB> 41 42
......
Object dump complete.

The CRT library counts all memory blocks allocated during program run, including memory allocated by the CRT library itself and other libraries, such as MFC. Therefore, an object with an assigned ordinal number of n is the nth object allocated in the program, but it is not necessarily the nth object assigned by the code. (This is not the case in most cases.) )
In this way, you can set a breakpoint at the allocated memory location using the allocation sequence number. method is to set a location breakpoint near the beginning of the program. When a program breaks at that point, you can set a memory allocation breakpoint from the QuickWatch (QuickWatch) dialog box or the Watch (watch) window:

For example, in the Watch window, type the following expression in the Name bar:

_crtbreakalloc

If you want to use the multithreaded DLL version of the CRT library (/md option), you must include the context operator, like this:

If you are using Visual C + + 4.0 or 4.1, write this:
{,, Msvcr40d.dll}*__p__crtbreakalloc ()
If you are using Visual C + + 4.2 or later, write this:
{,, Msvcrtd.dll}*__p__crtbreakalloc ()

Now press ENTER, the debugger calculates the value and puts the result in the Value column. If no breakpoint is set at the memory allocation point, the value is –1.
Replace the values in the Value column with the allocation ordinal of the memory allocation that you want to interrupt in its place. For example, enter 45. This will be interrupted where the assigned ordinal number is 45.
After you set breakpoints in the memory allocation that you are interested in, you can continue debugging. At this point, you must be careful when you run the program to ensure that the order in which the memory blocks are allocated does not change. When a program breaks at a specified memory allocation, you can view the call Stack window and other debugger information to determine when memory is allocated. If necessary, you can continue to execute the program from that point to see what happens to the object, perhaps to determine why the object was not properly disposed.
Although it is often easier to set memory allocation breakpoints in the debugger, you can set these breakpoints in your code if you prefer. In order to set a memory allocation breakpoint in your code, you can increase such a row (for the 45th memory allocation):

_crtbreakalloc = 45;

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

_CrtSetBreakAlloc (45);

How to compare memory status.


Another way to locate a memory leak is to get a snapshot of the application's memory state at a critical point. The CRT library provides a structure type _CrtMemState. You can use it to store snapshots of the memory state:

_CrtMemState S1, S2, S3;

To get a memory state snapshot to a fixed-point, you can pass a _crtmemstate structure to the _CrtMemCheckpoint function. This function fills this structure with a snapshot of the current memory state:

_CrtMemCheckpoint (&AMP;S1);

By passing the _crtmemstate structure to the _CrtMemDumpStatistics function, you can dump the contents of the structure anywhere:

_CrtMemDumpStatistics (&AMP;S1);

This function outputs dump memory allocation information in the following format:
0 bytes in 0 free Blocks.
Bytes in 3 Normal Blocks.
5037 bytes in Blocks CRT.
0 bytes in 0 Ignore Blocks.
0 bytes in 0 Client Blocks.
Largest number used:5308 bytes.
Total allocations:7559 bytes.

To determine whether a memory leak has occurred in a piece of code, you can compare the two states by getting the memory state snapshots that precede and after the segment code, and then using _crtmemdifference:

_CrtMemCheckpoint (&AMP;S1); Get first memory state snapshot

To allocate memory here
.........................................

_CrtMemCheckpoint (&AMP;S2); Get second memory state snapshot

Compare the differences between two memory snapshots
if (_CrtMemDifference (&AMP;S3, &AMP;S1, &AMP;S2))
{
_CrtMemDumpStatistics (&AMP;S3); Dump Variance Results
}

As the name suggests, _CrtMemDifference compares two memory states (the first two) to produce a result of the difference between the two states (the third argument). Placing _CrtMemCheckpoint calls at the beginning and end of a program and using _CrtMemDifference to compare results is another way to check for memory leaks. If a leak is detected, you can use the _CrtMemCheckpoint call to split the program and locate the leak by using binary search techniques.

Conclusions

Although VC + + has a set of specialized debugging MFC application mechanism, but this article discussed the memory allocation is very simple, does not involve MFC objects, so these content also applies to MFC programs. In the MSDN Library you can find a lot of information on the debugging of VC + +, if you can make good use of the MSDN Library, I believe that not much time you can become a debugging master.

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.