Memory leak detection under the Windows platform

Source: Internet
Author: User
Tags valgrind

One, memory leak detection under Windows platform

Detect memory leak issues

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 // Map 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. <stdlib.h>// map malloc and free functions to their debug versions, _malloc_dbg and _free_dbg,   These two functions will track memory allocations and releases. This mapping occurs only in the debug version (where _DEBUG is defined). The release version uses the normal malloc and free functions. 

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 ();

Cases

#define_crtdbg_map_alloc#include<stdlib.h>#include<crtdbg.h>#include<iostream>using namespacestd;voidGetMemory (Char*p,intnum) {P= (Char*)malloc(sizeof(Char) * num);//It can be detected with new.} intMainintargcChar**argv) {    Char*str =NULL; GetMemory (str, -); cout<<"Memory leak test!"<<Endl;    _CrtDumpMemoryLeaks (); return 0;}

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).
      • "Free blocks" are blocks of memory that have been freed. does not appear in the memory leak report.
      • 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 in hexadecimal form.

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 _CrtDumpMemoryLeaks when the program exits.

Locate the specific memory leak place

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.

A technique for locating memory leaks is to take a snapshot of the memory state. 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, such as placing a _crtmemcheckpoint call at the beginning and end of the program, and using _ Crtmemdifference comparison results, if a leak is detected, you can use the _CrtMemCheckpoint call to divide the program and locate the leak by using binary search techniques.

#define_crtdbg_map_alloc#include<stdlib.h>#include<crtdbg.h>#include<iostream>using namespacestd; _crtmemstate s1, S2, S3;//a snapshot of the _crtmemstate structure used to store memory states voidGetMemory (Char*p,intnum) {P= (Char*)malloc(sizeof(Char) *num);} intMainintargcChar**argv) {_CrtMemCheckpoint (&AMP;S1);//_CrtMemCheckpoint () to take a memory snapshot    Char*str =NULL; GetMemory (str, -); _CrtMemCheckpoint (&S2); if(_CrtMemDifference (&AMP;S3, &AMP;S1, &AMP;S2))//Crtmemdifference compares two memory states (S1 and S2), resulting in a difference between the two states (S3)_CrtMemDumpStatistics (&AMP;S3);//Dump S3 Contentcout<<"Memory leak test!"<<Endl;    _CrtDumpMemoryLeaks (); return 0;}

The output is as follows

Second, memory leak detection under Linux platform

The VS method is a hook for malloc and free to record memory allocation information.

Linux below also has the same principle method--mtrace,http://en.wikipedia.org/wiki/mtrace.

Another way is to use the Valgrind tool http://valgrind.org/docs/manual/manual.html

Memory leak detection under the Windows platform

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.