C + + memory leak and detection tool detailed _c language

Source: Internet
Author: User
Tags assert

First we need to know if the program has a memory leak, and then locate which line of code is leaking memory so that it can be repaired.

The simplest method of course is the use of professional testing tools, more famous such as Boundscheck, the function is very strong, I believe that people do C + + development can not be separated from it. In addition, you do not use any of the tools, but to implement the memory leak monitoring, in the following two cases:

I. Detecting memory leaks in MFC

If it is the use of MFC program, very simple. The default is a memory leak detection function.

We use VS2005 to generate an MFC dialog box program, found that he can automatically detect memory leaks. We don't have to do any special operations. Carefully observed, found in each CPP file, there are the following code:

Copy Code code as follows:

#ifdef _DEBUG
#define NEW Debug_new
#endif

DEBUG_NEW This macro is defined in the Afx.h file, which helps us locate the memory leak.

In the CPP file containing the above code after allocating memory, if not deleted, then stop the program, Visual Studio Output window will display the following information:

Detected memory leaks!
Dumping Objects->
D:\code\mfctest\mfctest.cpp: {157} normal block at 0x003af170, 4 bytes long.
Data: < > 00 00 00 00
Object dump complete.

Double-click on the line in the Output window, and the IDE opens the file and navigates to the row, which makes it easy to see where the memory leak occurred.

Two Detect memory leaks for pure C + + programs

I tried it. The Win32 Console application and Win32 Project project, created with Visual Studio, do not detect memory leaks.

The following step-by-step procedures for the memory leak detection mechanism to establish.

First, we need to know that the debug version of the C Run-time Library provides a number of detection features that make it easier for us to debug programs. There are special chapters in MSDN for this, called debug routines, which suggest you look at the contents first.

We're going to use a couple of functions that are important inside. One of the most important is _crtdumpmemoryleaks (), see the MSDN Help. To use this function, you need to include the header file Crtdbg.h

This function is only available in the debug version, and when you run the program under the debugger, _CrtDumpMemoryLeaks displays the memory leak information in the Output window. Write a paragraph code to test it, as follows:

Detect memory leaks Version one:

Copy Code code as follows:

#include "stdafx.h"
#include <crtdbg.h>
int _tmain (int argc, _tchar* argv[])
{
int* p = new int ();
_CrtDumpMemoryLeaks ();
return 0;
}

After running, in the Output window, the following information is displayed:

Detected memory leaks!
Dumping Objects->
{112} normal block at 0x003aa770, 4 bytes long.
Data: < > 00 00 00 00
Object dump complete.

But this just tells us that the program has a memory leak, in the end where the leak is not a glance out AH.

Look at our test memory leak version two:

Copy Code code as follows:

#include "stdafx.h"
#ifdef _DEBUG
#define Debug_clientblock New (_client_block, __file__, __line__)
#else
#define Debug_clientblock
#endif
#define _crtdbg_map_alloc
#include <crtdbg.h>
#ifdef _DEBUG
#define NEW Debug_clientblock
#endif
int _tmain (int argc, _tchar* argv[])
{
int* p = new int ();
_CrtDumpMemoryLeaks ();
return 0;
}

The program defines a few macros that are replaced by a macro with new under the Debug version, and a newer record of the file name and line of code when the call is made. After running, you can see the following results:

Detected memory leaks!
Dumping Objects->
D:\code\consoletest\consoletest.cpp: {112} client block at 0x003a38b0, subtype 0, 4 bytes long.
Data: < > 00 00 00 00
Object dump complete.

Oh, and MFC programs have the same effect, but wait a minute. Look at the following code:

Copy Code code as follows:

int _tmain (int argc, _tchar* argv[])
{
int* p = new int ();
_CrtDumpMemoryLeaks ();
Delete p;
return 0;
}

After running, we can see that we have removed the pointer, but it still reports a memory leak. So it can be imagined that every time you call new, the call will be recorded inside the program, similar to the number of records, if delete, then remove it from the array, and _CrtDumpMemoryLeaks () is the current state of the array print out.

So in addition to dump out memory information when necessary, the most important thing is to drop the _CrtDumpMemoryLeaks when the program exits ();

If the program has more than one exit, then we need to call the function in multiple places.

Further, what if the program deletes pointers in the destructor of the class? For example:

Copy Code code as follows:

#include "stdafx.h"
#ifdef _DEBUG
#define Debug_clientblock New (_client_block, __file__, __line__)
#else
#define Debug_clientblock
#endif
#define _crtdbg_map_alloc
#include <crtdbg.h>
#ifdef _DEBUG
#define NEW Debug_clientblock
#endif
Class Test
{
Public
Test () {_p = new int (); }
~test () {delete _p; }
int* _p;
};
int _tmain (int argc, _tchar* argv[])
{
int* p = new int ();
Delete p;
Test T;
_CrtDumpMemoryLeaks ();
return 0;
}

You can see the destructor is called when the program exits, there is no memory leak, but this writing is still reported.

How to improve, see detect memory leaks version three:

Copy Code code as follows:

#include "stdafx.h"
#ifdef _DEBUG
#define Debug_clientblock New (_client_block, __file__, __line__)
#else
#define Debug_clientblock
#endif
#define _crtdbg_map_alloc
#include <crtdbg.h>
#ifdef _DEBUG
#define NEW Debug_clientblock
#endif
Class Test
{
Public
Test () {_p = new int (); }
~test () {delete _p; }
int* _p;
};
int _tmain (int argc, _tchar* argv[])
{
_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _crtdbg_leak_check_df);
int* p = new int ();
Delete p;
Test T;
return 0;
}

_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _crtdbg_leak_check_df); This statement automatically invokes _CrtDumpMemoryLeaks when the program exits. Both _CRTDBG_ALLOC_MEM_DF and _CRTDBG_LEAK_CHECK_DF must be set.

In this way, this version has reached the same effect as MFC, but I think the light is not enough, because we are only in the Output window information, the developer's reminder is not obvious, often overlooked, and many people even found that the memory leak, but not easy to repair, does not seriously affect the external performance of the program, will not be repaired. How do you get developers to proactively fix the problem of memory leaks? I remember working with people to write programs, my function parameters are required, can not be empty, but others always send null value, there is no way, had to start validating the function parameters, to his assert live, so that the program is always running constantly pop-up assert, debugging program that annoying pressure, and finally other programmers annoying, Just change the problem, and the input parameters are correct. So I think I want to let the programmer take the initiative to do one thing, first of all, let him feel that doing this is to reduce their own burden, to make their work easy. Oh, so we also, when the program exits, detect memory leaks Let the program prompt out.

See detect memory Leaks version four:

Copy Code code as follows:

#include "stdafx.h"
#include <assert.h>
#ifdef _DEBUG
#define Debug_clientblock New (_client_block, __file__, __line__)
#else
#define Debug_clientblock
#endif
#define _crtdbg_map_alloc
#include <crtdbg.h>
#ifdef _DEBUG
#define NEW Debug_clientblock
#endif
void Exit ()
{
int i = _CrtDumpMemoryLeaks ();
assert (i = = 0);
}
int _tmain (int argc, _tchar* argv[])
{
Atexit (Exit);
int* p = new int ();
return 0;
}

This version checks for memory leaks when the program exits, and pops up the prompt dialog box if it exists.

Atexit (exit), which is set to execute the exit () function when the program exits. In the Exit () function, if there is a memory leak, _CrtDumpMemoryLeaks () returns a value other than 0, and it will be assert.

This version is already up to the point of use. But we can also make some improvements, because it is true to detect all the memory leaks in the code, need to put the code in the #define ... Copy to all files that use new. It is not possible to copy so many code in each file, so we can extract it and put it in a file, such as I am in KDetectMemoryLeak.h, which reads as follows:

Copy Code code as follows:

#pragma once
#ifdef _DEBUG
#define Debug_clientblock New (_client_block, __file__, __line__)
#else
#define Debug_clientblock
#endif
#define _crtdbg_map_alloc
#include <stdlib.h>
#include <crtdbg.h>
#ifdef _DEBUG
#define NEW Debug_clientblock
#endif

The KDetectMemoryLeak.h is then included in the project's common file, such as a project with VS, which is included in the stdafx.h. Or I built myself a Common.h file that contains some generic code that basic all files will use.

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.