C + + memory leak and detection

Source: Internet
Author: User

Recommended:

Http://www.cnblogs.com/skynet/archive/2011/02/20/1959162.html

Direct copy came, but before the study, just forget it, forgive this lazy ha.

Memory leak detection under the Windows platform

The Visual Studio debugger and the C run-time (CRT) library below the Windows platform provide us with an effective way to detect and identify memory leaks in the following principles: Memory allocations are implemented through the CRT at runtime, as long as they are recorded separately when allocating memory and freeing memory. At the end of the program, you can determine if there is a memory leak by comparing the records that allocate memory and free memory. The methods for enabling memory detection in VS are as follows:

    • STEP1, the following statements are included in the program: (#include statements must take the order shown above. If you change the order, the function that you use may not work correctly. )

#define _CRTDBG_MAP_ALLOC

#include <stdlib.h>

#include <crtdbg.h>

By including Crtdbg.h, the malloc and free functions are mapped to their debug versions, _malloc_dbg and _free_dbg, which track memory allocations and releases. This mapping occurs only in the debug version (where _DEBUGis defined). The release version uses the normal malloc and free functions.

The #define statement maps the base version of the CRT heap function to the corresponding "Debug" version. The statement is not absolutely necessary, but the memory leak dump contains less useful information if the statement is not available.

    • STEP2, after you add the above statement, you can dump the memory leak information by including the following statement in your program, which should normally be placed exactly before the program exits location:

_CrtDumpMemoryLeaks();

At this point, the complete code is as follows:

#define _CRTDBG_MAP_ALLOC

#include <stdlib.h>

#include <crtdbg.h>

#include <iostream>

usingnamespace std;

voidGetMemory(char *p, int num)

{

p = (char*)malloc(sizeof(char) * num);

}

intmain(int argc,char** argv)

{

char*str = NULL;

GetMemory(str, 100);

cout<<"Memory leak test!"<<endl;

_CrtDumpMemoryLeaks();

return0;

}

When you run the program under the debugger, _CrtDumpMemoryLeaks displays the memory leak information in the Output window. The memory leak information is as follows:

If you do not use the #define _CRTDBG_MAP_ALLOC statement, the memory leak dump will resemble the following:

When _crtdbg_map_alloc is undefined, it displays:

    • The memory allocation number (within curly braces).

    • Block type (normal, client, or CRT).

  • "Normal block" is the normal memory allocated by the program.

  • A "client block" is a special type of memory block used by an MFC program for objects that require destructors. The MFC new operation creates a normal block or client block based on the needs of the object being created.

  • A "CRT block" is a block of memory allocated by the CRT library for its own use. The CRT library handles the release of these blocks, so you are unlikely to see them in a memory leak report unless a critical error occurs (such as a corrupted CRT library).

The following two types of blocks are not seen in the memory leak information:

  • "Free blocks" are blocks of memory that have been freed.

  • The Ignore block is a block that you have specifically tagged, so it does not come out of the memory leak report.

    • The memory location in hexadecimal form.

    • The block size in bytes.

    • The first 16 bytes of content (also 16 binary).

When _CRTDBG_MAP_ALLOC is defined, it also displays the files in which the leaked memory is allocated. The number in parentheses after the file name (10 in this example) is the line number in the file.

Note: Calling _CrtDumpMemoryLeaks will be very easy if the program always exits in the same location. If the program exits from multiple locations, you do not need to place a call to _CrtDumpMemoryLeaks at each possible exit, and you can include the following call at the beginning of the program:

_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

The statement automatically calls _CrtDumpMemoryLeakswhen the program exits. You must set both the _CRTDBG_ALLOC_MEM_DF and the _crtdbg_leak_check_df two bit fields as shown earlier.

From the above method, we can almost locate where to call the memory allocation function malloc and new, such as the GetMemory function in the example above, that is, line 10th! However, it is not possible to locate where the memory leaks caused by getmemory () are called, and there may be many calls to getmemory in large projects. How do I navigate to where to call getmemory-caused memory leaks?

Another technique for locating a memory leak involves taking a snapshot of the memory state of the application at a critical point. The CRT library provides a structure type _crtmemstate, which you can use to store snapshots of the state of memory:

_CrtMemState s1, s2, s3;

To take a snapshot of the memory state at a given point, pass the _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 at any point:

_CrtMemDumpStatistics( &s1 );

To determine if a memory leak has occurred in a part of your code, you can take a snapshot of the memory state before and after that section, and then use _CrtMemDifference to compare the two states:

_CrtMemCheckpoint( &s1 );

// memory allocations take place here

_CrtMemCheckpoint( &s2 );

if( _CrtMemDifference( &s3, &s1, &s2) )

_CrtMemDumpStatistics( &s3 );

As the name implies,_crtmemdifference compares the two memory states (S1 and S2) to produce a result of the difference between the two states (S3). 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 divide the program and locate the leak using binary search techniques.

As the above example program we can do this to locate the exact place to call GetMemory:

#define _CRTDBG_MAP_ALLOC

#include <stdlib.h>

#include <crtdbg.h>

#include <iostream>

usingnamespace std;

_CrtMemState s1, s2, s3;

voidGetMemory(char *p, int num)

{

p = (char*)malloc(sizeof(char) * num);

}

intmain(int argc,char** argv)

{

_CrtMemCheckpoint( &s1 );

char*str = NULL;

GetMemory(str, 100);

_CrtMemCheckpoint( &s2 );

if( _CrtMemDifference( &s3, &s1, &s2) )

_CrtMemDumpStatistics( &s3 );

cout<<"Memory leak test!"<<endl;

_CrtDumpMemoryLeaks();

return0;

}

When debugging, the program outputs the following results:

This means there is a memory leak between S1 and S2!!! If GetMemory is not called between S1 and S2, then there will be no information output.

C + + memory leak and detection

Related Article

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.