VC Memory Leak Check tool: Visualleakdetector

Source: Internet
Author: User
Tags int size readable

Visualleakdetector flexible Freedom is a major feature of C/s + + language, and this is a difficult problem for C + + programmers. When the program becomes more and more complex, memory management will become more complex, a little careless will appear memory problems. Memory leaks are one of the most common memory problems. Memory leaks if not very serious, in a short period of time will not have much impact on the program, which also makes the memory leak problem has a strong concealment, not easy to be found. However slight the memory leak, when the program runs for a long time, its destructive power is staggering, from performance down to memory exhaustion, and even to the normal operation of other programs. Another common feature of the memory problem is that the memory problem itself does not have a very obvious phenomenon, when there is abnormal phenomenon has changed, its site has not occurred when the problem of the scene, which gives debugging memory problems brought great difficulty.

Visualleakdetector is a free memory leak detection tool for visualc++. Can be downloaded in the VISUALLEAKDETECTOR1.9-VC memory leak checking tool. Compared to other memory leak detection tools, it also has the following characteristics when detecting memory leaks:

1, can get the memory leak point of the call stack, if you can, you can also get the file and line number;

2, can get the complete data leaking memory;

3, can set the level of memory leakage report;

4, it is a packaged lib, use without compiling its source code. And for the user's own code, but also need to make a small change;

5, his source code is issued using the GNU license and has detailed documentation and comments. It's a good choice for readers who want to get a better understanding of heap memory management. Visible, from the use point of view, Visualleakdetector simple and easy to use, for the user's own code, the only modification is #includevisualleakdetector the first file after the normal operation of their own program, you can find memory problems. From the perspective of research, if deep visualleakdetector source code, you can learn the principle of heap memory allocation and release, memory leak detection principle and memory operation of the common skills. This article will first introduce the use of visualleakdetector and procedures, and then together with the reader preliminary study Visualleakdetector source code, to understand the visualleakdetector work principle. Using Visualleakdetector (1.0) Let's show you how to use this compact tool. First download the ZIP package from the Web site, decompression after the Vld.h,vldapi.h,vld.lib,vldmt.lib,vldmtdll.lib,dbghelp.dll and other documents. Copy the. h file to the default include directory of visualc++, and then copy the. lib file to the visualc++ default Lib directory, and the installation is complete. Because of the version problem, if you use a windows2000 or a previous version, you need to copy the Dbghelp.dll to the running directory of your program, or to any other directory that you can refer to.


Next needs to be added to its own code. Method is simple, as long as you include Vld.h in the. cpp file that contains the entry function. If the CPP file contains stdafx.h, the statement containing the vld.h is placed after the stdafx.h containing statement, otherwise put in the front. The following is an example program: #includevoidmain () {...} Next, let's demonstrate how to use Visualleakdetector to detect memory leaks. The following is a simple program that allocates a heap memory of int size with new, and is not released. The memory address of its application is printed to the screen with printf. #include #include#includevoidf () {int*p=newint (0x12345678);p rintf ("p=%08x,", p);} Voidmain () {f ();} After compiling, it is obtained in the standard Output window: P=003A89C0 is obtained in the Output window of visualc++: Warning:visualleakdetectordetectedmemoryleaks!---------- Block57at0x003a89c0:4bytes------------57th Block 0x003a89c0 address leaked 4 bytes callstack:--The following is the call stack D:testtestvldconsole Testvldconsolemain.cpp (7): f--represents the F () function D:test testvldconsoletestvldconsolemain.cpp in line 7th of main.cpp: main– Double-click to boot to the corresponding code at F:RTM vctoolscrt_bldself_x86crtsrccrtexe.c (586): __tmaincrtstartupf:rtm vctoolscrt_bldself_x86crtsrc CRTEXE.C (403): maincrtstartup0x7c816d4f (fileandlinenumbernotavailable): registerwaitforinputidledata:--This is the content of the leaking memory , 0x1234567878563412xv4 ....... Visualleakdetectordetected1memoryleak. The second line indicates that block 57th has 4 bytes of memory leak, the address is 0x003a89c0, according to the program console output, you can know that the address is the pointer p. RideIn the 7th line of the order, in the F () function, 4 bytes of heap memory space is allocated at this address, and the value is 0x12345678, so that we see the same content in the 4 bytes in the report.

As you can see, for each memory leak, this report lists its leak point, length, call stack when allocating that memory, and the contents of the leaked memory (listed in 16 and text format, respectively). Double-clicking on a row of the stack report automatically jumps to the corresponding row of the file that it refers to in the Code Editor. This information will be of great help when we look for memory leaks. This is a very easy to use tool, every time after installation, you just need to include its header file in a rebuild. Also, the tool will only be connected to your program in the Builddebug version, and if the Buildrelease version, the tool will not have any performance impact on your program. So you can always include the header file in your source code. Visualleakdetector working principle let's look at how the tool works. Before we go, let's take a look at how the visualc++ built-in memory leak detection tool works. Visualc++ Built-in tools crtdebugheap work is simple. When allocating memory using the debug version of malloc, malloc records the file name and line number allocated for that memory in the header of the memory block. When the program exits, the CRT does some cleanup work after the main () function returns, checking the debug heap memory, and there must be a memory leak if the memory is still not released. From the headers of the memory blocks that are not freed, you can get the file name and line number.

This static method detects the file name and line number of a memory leak and its leaking point, but does not know exactly how the leak occurred and does not know how the memory allocation statement was executed. To understand these, you must dynamically track the program's memory allocation process. That's what Visualleakdetector did. It records its context every time the memory is allocated, and when the program exits, detects the memory leaks, finds the contextual information it has logged, and converts it to the report output. Initialize Visualleakdetector to record each memory allocation, and how does it monitor memory allocations? Windows provides an allocation hook (allocationhooks) to monitor the allocation of debug heap memory. It is a user-defined callback function that is invoked each time the memory is allocated from the debug heap. When initialized, Visualleakdetector uses _CrtSetAllocHook to register the hook function so that you can monitor all heap memory allocations since then. How do I guarantee that there are no heap memory allocations before Visualleakdetector initialization? Global variables are initialized when the program starts, and if you use Visualleakdetector as a global variable, you can start it with the program. However, C + + does not contract the initialization order between global variables, which may not be detectable if there are heap memory allocations in the constructors of other global variables.

Visualleakdetector uses the #pragmainit_seg provided by C/p + + to somewhat reduce the probability that other global variables will initialize before them. According to the definition of #pragmainit_seg, the initialization of global variables is divided into three stages: first, compiler segment, General C language Run-time library initialization at this time, then Lib section, generally used for third party class library initialization, etc., and finally the user segment, Most of the initialization is done at this stage. Visualleakdetector is initialized to the compiler segment, so that it is initialized before most global variables and almost all user-defined global variables. Record memory allocation an allocation hook function needs to have the following form: Intyourallochook (Intalloctype,void*userdata,size_tsize,intblocktype,longrequestnumber, Constunsignedchar*filename,intlinenumber); As mentioned earlier, it is registered at Visualleakdetector initialization and is invoked each time before allocating memory from the debug heap. What this function needs to handle is to record the call stack at this point and the unique identification--requestnumber for this heap memory allocation. Getting the binary representation of the current stack is not a very complex thing, but because the stack content generated by different architectures, different compilers, and different function calling conventions is slightly different, it is slightly more complicated to interpret the stack and get the entire function call procedure. However, Windows provides a StackWalk64 function to get the contents of the stack. STACKWALK64 's statement is as follows: BOOLStackWalk64 (Dwordmachinetype,handlehprocess,handlehthread,lpstackframe64stackframe, Pvoidcontextrecord,


pget_module_base_routine64getmodulebaseroutine,ptranslate_address_routine64translateaddress); The STACKFRAME64 structure represents a frame in the stack. Give the initial STACKFRAME64, call the function repeatedly, you can get the memory allocation point of the call stack. Walkthestack.while (count<_vld_maxtraceframes) {count++;if (!pstackwalk64 architecture,m_process,m_thread, &FRAME,&CONTEXT,NULL,PSYMFUNCTIONTABLEACCESS64,

Psymgetmodulebase64,null)) {//couldn ' ttracebackthroughanymoreframes.break;} if (frame. addrframe.offset==0) {//endofstack.break;} Pushthisframe ' Sprogramcounterontotheprovidedcallstack.callstack->push_back (DWORD_PTR) frame. Addrpc.offset);}

So, how do you get the initial STACKFRAME64 structure? In the STACKFRAME64 structure, other information is relatively easy to obtain, and the current program counter (EIP) in the x86 architecture can not be directly read through the software method. Visualleakdetector uses a method to get the current program counter. First, it calls a function, then the return address of the function is the current program counter, and the return address of the function can be easily obtained from the stack. The following is the program that Visualleakdetector obtains the current program counter: #ifdefined (_m_ix86) | | Defined (_m_x64) #pragmaauto_inline (off) dword_ptrvisualleakdetector::getprogramcounterx86x64 () {Dword_ Ptrprogramcounter;__asmmovaxreg, [bpreg+sizeofptr]//getthereturnaddressoutofthecurrentstackframe__asmmov[ Programcounter],axreg//putthereturnaddressintothevariablewe ' Llreturnreturnprogramcounter;} #pragmaauto_inline (ON) #endif//defined (_m_ix86) | | Defined (_m_x64) gets the call stack, which naturally has to be recorded. Visualleakdetector uses a map-like data structure to record this information. This makes it easy to find its call stack from the RequestNumber. The Alloctype parameter of the allocation hook function represents the type of memory allocation for this heap, including _hook_alloc,_hook_realloc, and _hook_free, and the following code is the visualleakdetector handling of various situations. Switch (type) {case_HOOK_ALLOC:visualleakdetector.hookmalloc (request); Break;case_hook_free: Visualleakdetector.hookfree (pdata); break;

Case_HOOK_REALLOC:visualleakdetector.hookrealloc (pdata,request); Break; (" WARNING:


Inallochook (): Unhandledallocationtype (%d). N ", type); Here, the Hookmalloc () function gets the current stack and joins the current stack and requestnumber into a map-like data structure. The Hookfree () function deletes this information from a map-like data structure. The Hookrealloc () function calls Hookfree () and Hookmalloc () in turn.

Detecting memory leaks The previous reference to the visualc++ built-in memory leak detection tool works. As with this principle, because global variables are structured in the opposite order, when Visualleakdetector destructors, almost all of the other variables have been refactored, and if there is still an unbound heap of memory, it must be a memory leak. The allocated heap memory is organized by a linked list, and checking the memory leak checks the list. However, Windows does not provide a way to access this list. Visualleakdetector used a little trick to get it. To first request a piece of temporary memory on the heap, the address of the memory can be converted to point to a _crtmemblockheader structure in which the list can be obtained. The code is as follows: Char*pheap=newchar;_crtmemblockheader*pheader=phdr (pheap)-> pblockheadernext;deletepheap; Where Pheader is the first pointer of the linked list. Report generation Visualleakdetector How to detect, log memory leaks, and their call stacks. But if this information is to be useful to programmers, it must be converted into a readable form. Visualleakdetector uses SymGetLineFromAddr64 () and symfromaddr () to generate a readable report. Iteratethrougheachframeinthecallstack.for (frame=0;frame

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: 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.