Detect a memory leak with code on Windows by define _CRTDBG_MAP_ALLOC macros

Source: Internet
Author: User

With the memory leak detection tool in VS, to enable memory leak detection, include the following statement in your program:

#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>

Their order of precedence cannot be changed. By including Crtdbg.h, the malloc and free functions are mapped to their "Debug" version _malloc_dbg and _free_dbg, which track memory allocation and release. This mapping occurs only in the debug version (where _DEBUG is defined). #define语句将CRT堆函数的基版本映射到对应的 "Debug" version.

The test code is as follows:

#include <iostream>

#ifdef _DEBUG
	#define Debug_clientblock   New (_client_block, __file__, __line__ )
#else
	#define Debug_clientblock
#endif

#ifdef _DEBUG
	#define _CRTDBG_MAP_ALLOC
	#include <crtdbg.h>

	#define NEW Debug_clientblock
#endif

void Test_c ()
{
	int* p = (int*) malloc ( sizeof (int));

	Free (p);
}

void Test_cpp ()
{
	int* p = new INT[10];

	delete [] p;
}

int main ()
{
	_CrtSetDbgFlag (_crtdbg_alloc_mem_df | _crtdbg_leak_check_df);//_crtdumpmemoryleaks ()
	; _CrtSetReportMode (_crt_error, _crtdbg_mode_debug);

	Test_c ();
	Test_cpp ();

	Std::cout << "OK" << Std::endl;
}
The result diagram is as follows:


GitHub: https://github.com/fengbingchun/Messy_Test

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.