Use VS to detect memory leaks

Note: It can only be used in the Debug mode of VS

How to use:

Make these lines appear at the top of all .cpp files.
The method is as follows:
If there is only one cpp file, just put it on the top
If there are multiple cpp files, write a header file, write it at the top of the header file, and then let all cpp files include this header file

#define _CRTDBG_MAP_ALLOC   //必须放在#include<crtdbg.h>之前
#include <crtdbg.h>
#include <stdlib.h>
#define NEW_WITH_MEMORY_LEAR_CHECKING new(_NORMAL_BLOCK,__FILE__,__LINE__)
#define new NEW_WITH_MEMORY_LEAR_CHECKING

Then add before return 0 of the main function

_CrtDumpMemoryLeaks();

When running like this, the memory leak information (object length, the value of the first few bytes) will be output from the output window!

example:

#define _CRTDBG_MAP_ALLOC   //必须放在#include<crtdbg.h>之前
#include <crtdbg.h>
#include <stdlib.h>
#define NEW_WITH_MEMORY_LEAR_CHECKING new(_NORMAL_BLOCK,__FILE__,__LINE__)
#define new NEW_WITH_MEMORY_LEAR_CHECKING

int main(int argc, char* argv) {
    
    
    auto p = new int[10];
    //delete[] p;   //申请了内存但没有释放
    
	_CrtDumpMemoryLeaks();
	return 0;
}

Output:
insert image description here
It can be seen that the above program leaks 40 bytes of memory, which is consistent with the actual situation.

It should be noted that relevant information will be output when _CrtDumpMemoryLeaks(); is called, and _CrtDumpMemoryLeaks(); is placed before return 0;, so if we use smart pointers in main(), memory leaks will be displayed, but they will not actually (provided there is no misuse of smart pointers), because the smart pointers in main() will end when the scope of main() ends (that is, after return 0). So to test the smart pointer should be placed in the local scope (that is, write a function and then call it in main(), or directly { ... }).
Recommended practice:

#define _CRTDBG_MAP_ALLOC   //必须放在#include<crtdbg.h>之前
#include <crtdbg.h>
#include <stdlib.h>
#define NEW_WITH_MEMORY_LEAR_CHECKING new(_NORMAL_BLOCK,__FILE__,__LINE__)
#define new NEW_WITH_MEMORY_LEAR_CHECKING

#include <iostream>
#include <memory>

//智能指针的操作放在这个局部作用域中
void func() {
    
    
    //TODO
	auto p = std::make_shared<int>(10);

	return;
}

int main() {
    
    	
	func();
 
	_CrtDumpMemoryLeaks();
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43003108/article/details/121099729