VC + + 6.0 How to use the CRT debugging features to detect memory leaks __c++

Source: Internet
Author: User
First, the basic tools for detecting memory leaks are the debugger and the CRT debug heap functions. In order to use the debug heap function, you must add the following statement to the program in which you want to detect memory leaks and debugging:

#define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include "debug_new.h"

MSDN says: "The order of the declarations must be guaranteed, and if the order is changed, it may not work properly." "As to why this is, we know not. The bosses of MS are often so mysterious.

For non-MFC programs, plus the star of the week's header file: Debug_new.h, of course, if you do not add this sentence, you can detect memory leaks, but you can not determine in which source program file leaks. Output outputs only tell you that there is a memory leak somewhere in the crtsdb.h. Reg_debug_new didn't work when I tested it. Adding this macro can detect a file that has a memory allocation leak.

Second, once you add the above statement, you can report the memory leak information by adding the following code to the program:

_CrtDumpMemoryLeaks (); It's so simple. I joined these agencies in the example code of the week star, and in the VC + + debugging session (press F5 debug Run) the Debug page of Output window will see the expected memory leak dump. The dump form is as follows:

Detected memory leaks! Dumping Objects-> C:/Program files/.../include/crtdbg.h (552): {{} normal block at 0x00441ba0, 2 bytes long. Data: <AB> c:/program files/.../include/crtdbg.h (552): {{} normal block at 0x00441bd0, bytes long. Data: < C > CDs CD CDS CD CD CDS CD CD CD CD CD C:/Program files/.../include/crtdbg.h (552): {+} normal Block at 0x00441c20, bytes long. Data: < C > E8 (complete) in the following "".

For more specific details, refer to the source code files included with this article.

Here's how to detect a memory leak using the CRT debugging feature after I've looked at the MSDN data. "The problem has been compiled and sorted out, hope to be useful to everyone. If your English is great, then you don't have to look down and suggest you read the technical text in the MSDN library directly.

One of the most powerful features of the C + + programming language is its dynamic allocation and release of memory, but there is an old saying in China that "the greatest strengths can also be the greatest weakness", and that is what the C + + application confirms. The most common problem is the improper handling of memory that is dynamically allocated during the development of C + + applications. One of the most elusive and hardest to detect errors is a memory leak, a failure to properly dispose of previously allocated memory. Occasionally a small amount of memory leaks may not be noticed, but a program that leaks large amounts of memory or leaks a growing number of programs may show a variety of symptoms: from poor performance (and gradually decreasing) to full memory exhaustion. Worse, the leaking program may use too much memory, causing another program to collapse, leaving the user unable to find the real source of the problem. In addition, even harmless memory leaks can be implicating.

Fortunately, the Visual Studio debugger and the C run-time (CRT) library provide us with an effective way to detect and identify memory leaks. Here, share the harvest with me-how to use the CRT Debugging feature to detect memory leaks. How to enable the memory leak detection mechanism. Use _CrtSetDbgFlag to set the CRT reporting mode to interpret how the memory block type sets a breakpoint at the memory allocation ordinal. How to compare memory status. Conclusion

How to enable the memory leak detection mechanism.

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> c:/program files/microsoft Visual studio/vc98/include/crtdbg.h (552): {} normal block at 0x00441b D0, Bytes long. Data: < C > CDs CD CD CD CD CDs CD CD CD C:/Program files/microsoft visual STUDIO/VC98/INCLUDE/CR Tdbg.h (552): {{} normal block at 0x00441c20, bytes long. Data: < C (a) (complete), in the same.

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

Detected memory leaks! Dumping Objects->{45} normal block at 0x00441ba0, 2 bytes long. Data: <AB> {} normal block at 0x00441bd0, bytes long. Data: < C > CD CD CD CD CD, CD CD CD CD CD CD {n} normal block at 0x00441c20, bytes long.  Data: < C > C0 (complete) in the following "". 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 the bracket is the memory allocation sequence number, the example in this article is {45},{44},{43};block: the type of memory block, there are three kinds commonly used: normal (normal), clients (client) or CRT (runtime); In this example: normal block ; memory locations in hexadecimal format, such as: at 0X00441BA0, etc.; the size of the memory block 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 where the source program file allocates the memory (or you can select the row and press F4 to do the same). This makes it easy to locate where the memory leak is occurring, so the _crtdbg_map_alloc's 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: This is the memory allocated by your program. Client block (Customer blocks): This is a special type of memory block, specifically for objects in MFC programs 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 Blocks: A block of memory that has been freed. Ignore 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:

{,, Msvcrtd.dll}_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 (&S1);

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

_CrtMemDumpStatistics (&S1);

This function outputs dump memory allocation information in the following format:

0 bytes in 0 free blocks.75 bytes at 3 Normal blocks.5037 bytes in CRT blocks.0 bytes in 0 Ignore blocks.0 bytes in 0 C lient 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 (&S1)//Get the first memory state snapshot//Here for memory allocation _CrtMemCheckpoint (&S2);//Get the second memory state snapshot//Compare the difference of two memory snapshots if (_ Crtmemdifference (&S3, &S1, &s2)) _CrtMemDumpStatistics (&S3);//Dump difference result

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.

Conclusion

Although VC + + has a set of mechanisms specifically for debugging MFC applications, the memory allocations discussed above in this article are simple and do not involve MFC objects, so they also apply 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. &NBSP

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.