VLD (Visual Leak Detector) memory Leak Detection Tool

Source: Internet
Author: User

The first knowledge of visual Leak Detector
Flexible freedom is a major feature of the C + + language, and this is a problem for C + + programmers. When the program becomes more and more complex, memory management becomes more complex, and there is a slight memory problem. Memory leaks are one of the most common memory problems. Memory leaks if not very serious, in a short period of time on the program will not have much impact, which also makes the memory leak problem has a strong concealment, not easy to be discovered. However slight the memory leak, when the program is running for a long time, its destructive power is staggering, falling from performance to memory exhaustion, and even affecting the normal operation of other programs. In addition, a common feature of the memory problem is that the memory problem itself does not have a very obvious phenomenon, when there are anomalies occurred, the scene has not been the scene of the problem, which to debug memory problems brought a lot of difficulty.
Visual Leak detector is a free memory leak detection Tool for Visual C + +. Compared to other memory leak detection tools, it also has the following features when it detects a memory leak:
1, can get the memory leak point of the call stack, if possible, you can also get the file and line number;
2, can get the full data leakage memory;
3, can set the level of memory leakage report;
4, it is a package of LIB, use without compiling its source code. And for the user's own code, but also only need to make a small change;
5. His source code is published using the GNU license and has detailed documentation and comments. It's a good choice for readers who want to get a deeper understanding of heap memory management.
Visible, from the perspective of Use, Visual Leak detector simple and easy to use, for the user's own code, the only modification is the # include Visual Leak detector header files, you can find memory problems. From a research perspective, if you delve into the visual Leak detector source code, you can learn about the principles of heap memory allocation and release, the principles of memory leak detection, and common techniques for memory operations.
This article will first introduce the use of visual Leak detector and steps, and then together with the reader preliminary study of visual Leak detector source code, to understand how visual Leak detector works.
Using Visual Leak Detector (1.0)
Let's show you how to use this compact tool.
First download the zip package from the website, after decompression to get vld.h, vldapi.h, Vld.lib, Vldmt.lib, Vldmtdll.lib, Dbghelp.dll and other files. Copy the. h file to the default include directory for Visual C + +, and then copy the. lib file to the default Lib directory for Visual C + + and the installation is complete. Because of the version issue, if you use Windows 2000 or a previous version, you need to copy the Dbghelp.dll to the running directory of your program, or to other directories that you can refer to.
Next you need to add it to your code. The 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 it is placed at the front. Here is an example program:
#include <vld.h>
void Main ()
{
...
}
Next, let's demonstrate how to use visual Leak detector to detect memory leaks. Here is a simple program that allocates an int-sized heap memory with new and does not release it. Its requested memory address is output to the screen with printf.
#include <vld.h>
#include <stdlib.h>
#include <stdio.h>
void F ()
{
int *p = new int (0x12345678);
printf ("p=%08x,", p);
}
void Main ()
{
f ();
}
After the compilation is run, the standard Output window gets:
P=003a89c0
The Output window in Visual C + + gets:
Warning:visual Leak Detector detected memory leaks!
----------Block bytes at 0x003a89c0:4------------57th 0x003a89c0 address leaked 4 bytes
Call stack:--The following is the
D:\test\testvldconsole\testvldconsole\main.cpp (7): F--Represents the F () function in line 7th of Main.cpp
D:\test\testvldconsole\testvldconsole\main.cpp: main– Double-click to boot to the corresponding code
F:\RTM\VCTOOLS\CRT_BLD\SELF_X86\CRT\SRC\CRTEXE.C (586): __tmaincrtstartup
F:\RTM\VCTOOLS\CRT_BLD\SELF_X86\CRT\SRC\CRTEXE.C (403): mainCRTStartup
0x7c816d4f (File and line number not available): Registerwaitforinputidle
Data:-This is the content of the leaked memory, 0x12345678
The xV4 of the ..... .....
Visual Leak Detector detected 1 memory Leak.
The second line indicates that block 57th has a memory leak of 4 bytes, the address is 0x003a89c0, according to the output of the program console, you can know that the address is pointer p. The 7th line of the program, the F () function, allocates 4 bytes of heap memory space at that address and assigns a value of 0x12345678, so that in the report we see the same 4 bytes of content.
As you can see, for each memory leak, this report lists its leak point, its length, the call stack when the memory was allocated, and the contents of the leaked memory (listed in 16 binary and text format, respectively). Double-clicking on a row of the stack report automatically jumps to the corresponding line of the file it refers to in the Code Editor. This information will be of great help to us in looking for a memory leak.
This is an easy-to-use tool that, after installation, only needs to be included in the header file to re-build each time it is used. Moreover, the tool will only be connected to your program when the build debug version, if build release, the tool will not have any performance impact on your program. So you can always include its header file in your source code.
How Visual Leak Detector works
Let's take a look at how the tool works.
Before that, let's take a look at how the memory leak detection tool built into Visual C + + works. Visual C + + built-in tools for CRT Debug heap work were originally simple. When using the debug version of malloc to allocate memory, malloc records the file name and line number allocated to the memory in the header of the memory block. When the program exits, the CRT will do some cleanup work after the main () function returns, this time to check the debug heap memory, if there is still memory is not released, there must be a memory leak. From the header of these 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 the memory leak and its leak point, but does not know how the leak occurred and how the memory allocation statement was executed. To understand this, you have to dynamically track the program's memory allocation process. This is what Visual Leak detector did. It records the context of each memory allocation and, when the program exits, finds its recorded contextual information and translates it into report output for a detected memory leak.
Initialization
Visual Leak detector to record every memory allocation, and how does it monitor memory allocations? Windows provides an allocation hook (allocation hooks) to monitor the allocation of debug heap memory. It is a user-defined callback function that is called every time the memory is allocated from the debug heap. At initialization time, Visual Leak detector uses _CrtSetAllocHook to register this hook function so that it can monitor all heap memory allocations since then.
How do you ensure that there is no heap memory allocation before the Visual Leak detector is initialized? Global variables are initialized when the program starts, and if you use visual Leak detector as a global variable, you can start with the program. However, C + + does not contract the initialization order between global variables and may not be detected if there are heap memory allocations in the constructors of other global variables. Visual Leak Detector uses the #pragma init_seg provided by C/+ + to reduce to some extent the probability that other global variables will be initialized before them. According to the definition of #pragma init_seg, the initialization of global variables is divided into three stages: the first is the compiler segment, the General C language Runtime Library is initialized at this time, and then the Lib segment, which is generally used for the initialization of third-party class libraries, and so on; Finally, the user segment, Most of the initialization is done at this stage. Visual Leak Detector sets its initialization in the compiler segment, which makes it initialized before most global variables and almost all user-defined global variables.
Log Memory Allocations
An allocation hook function needs to have the following form:
int yourallochook (int alloctype, void *userdata, size_t size, int blocktype, long requestnumber, const unsigned char *fil ename, int linenumber);
As stated earlier, it is registered when the visual Leak detector is initialized, and is called each time it is allocated memory from the debug heap. The thing that this function needs to deal with IS to record the call stack at this time and the unique identifier--requestnumber for this heap memory allocation.
Getting the binary representation of the current stack is not a complex thing, but because different architectures, different compilers, different function calling conventions produce a slightly different stack content, it is slightly more complex to interpret the stack and get the entire function call process. However, Windows provides a StackWalk64 function to get the contents of the stack. STACKWALK64 's statement is as follows:
BOOL StackWalk64 (DWORD machinetype, HANDLE hprocess, HANDLE hthread, LPSTACKFRAME64 stackframe, PVOID Contextrecord, PREA D_process_memory_routine64 Readmemoryroutine, Pfunction_table_access_routine64 FunctionTableAccessRoutine, PGET_ Module_base_routine64 Getmodulebaseroutine, ptranslate_address_routine64 translateaddress); The STACKFRAME64 structure represents a frame in the stack. Given the initial STACKFRAME64, call the function repeatedly, you can get the memory allocation point of the call stack.
Walk the stack.
while (Count < _vld_maxtraceframes) {
count++;
if (!pstackwalk64 (architecture, M_process, M_thread, &frame, &context,
NULL, PSYMFUNCTIONTABLEACCESS64, pSymGetModuleBase64, null)) {
Couldn ' t trace back through any more frames.
Break
}
if (frame. Addrframe.offset = = 0) {
End of Stack.
Break
}
Push This frame ' s program counter onto the provided callstack.
Callstack->push_back ((DWORD_PTR) frame. Addrpc.offset);
}
So, how do you get the initial STACKFRAME64 structure? In the STACKFRAME64 structure, the other information is relatively easy to obtain, and the current program counter (EIP) in the x86 architecture can not be directly read by the software method. Visual Leak Detector uses a method to obtain 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. Here is the program that visual Leak detector obtains the current program counter:
#if defined (_m_ix86) | | Defined (_m_x64)
#pragma auto_inline (off)
Dword_ptr visualleakdetector::getprogramcounterx86x64 ()
{
Dword_ptr Programcounter;
__ASM mov axreg, [Bpreg + sizeofptr]/Get The return address out of the current stack frame
__ASM mov [programcounter], Axreg//Put The return address into the variable we ' ll return
return programcounter;
}
#pragma auto_inline (ON)
#endif//Defined (_m_ix86) | | Defined (_m_x64)
Gets the call stack, which naturally needs to be recorded. Visual Leak Detector uses a map-like data structure to record this information. This makes it easy to find the call stack from RequestNumber. The Alloctype parameter of the allocation hook function represents the type of this heap memory allocation, including _hook_alloc, _hook_realloc, and _hook_free, and the following code is a visual Leak detector 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
Default
Visualleakdetector.report ("Warning:visual Leak detector:in Allochook (): Unhandled allocation type (%d). \ n", type);
Break
}
Here, the Hookmalloc () function gets the current stack and joins the current stack with RequestNumber in a map-like data structure. The Hookfree () function removes this information from a map-like data structure. The Hookrealloc () function calls Hookfree () and Hookmalloc () in turn.
Detecting memory leaks
The memory leak detection tools built into Visual C + + are mentioned earlier. As with this principle, because global variables are refactored in the opposite order of construction, when the visual Leak detector is refactored, almost all other variables are already refactored, and if there is still a heap memory that is not freed, a memory leak is required.
The allocated heap memory is organized through a list of links, and checking for memory leaks is the list of checks. However, Windows does not provide a way to access the linked list. Visual Leak detector used a little trick to get it. To first request a temporary memory on the heap, the address of the memory can be converted to point to a _crtmemblockheader structure in which the linked list can be obtained. The code is as follows:
Char *pheap = new Char;
_crtmemblockheader *pheader = PhDr (pheap)->pblockheadernext;
Delete pheap;
Where Pheader is the first pointer to the list.
Report generation
Earlier, visual Leak detector how to detect, record, and its call stacks for memory leaks. But if this information is useful to programmers, it must be converted into a readable form. Visual Leak Detector uses SymGetLineFromAddr64 () and symfromaddr () to generate a readable report.
Iterate through each frame on the call stack.
for (frame = 0; frame < callstack->size (); frame++) {
Try to get the source file and line number associated with
This program counter address.
if (PSymGetLineFromAddr64 (m_process,
(*callstack) [Frame], &displacement, &sourceinfo) {
...
}
Try to get the name of the function containing
Counter address.
if (Psymfromaddr (m_process, (*callstack) [frame],
&displacement64, Pfunctioninfo)) {
functionname = pfunctioninfo->name;
}
else {
functionname = "(Function name unavailable)";
}
...
}
To summarize, the work of Visual Leak detector is divided into 3 steps, first registering a hook function in the initialization, and then the hook function is called to record the scene at the time of memory allocation; Finally check the heap memory allocation list to determine if it is There is a memory leak and the field of leaking memory is converted into a readable form output. Interested readers can read the source code of the visual Leak detector.
Summarize
In use, Visual Leak detector is simple and convenient, and the results report at a glance. In principle, the Visual Leak detector The characteristics of memory leak problem, can be described as the right remedy-memory leak is not easy to find? That is, every time the memory allocation is recorded, the program exits the general ledger, memory leaks when the phenomenon is not changed, is not the site of the leak point? Then record the scene, clearly telling the user that the leak of memory is in the process of a call to leak out.
Visual Leak Detector is an easy-to-use memory leak detection tool. Now the latest version is 1.9a, with a new detection mechanism and a lot of improvements in functionality. Readers may wish to experience it.

Note that the various versions of VLD apply to different VC vs compilers and choose the appropriate version.

Version 1.9 is suitable for VS2005.

Note the use of the Vld.ini configuration file

Visual Leak Detector 1.0 Downloads: http://download.csdn.net/detail/gordennizaicunzai/9438283

Transferred from: http://www.cnblogs.com/kex1n/archive/2011/05/31/2064717.html

http://blog.csdn.net/gordennizaicunzai/article/details/50367597

VLD (Visual Leak Detector) memory Leak Detection Tool

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.