Get the App
SLTechnology News&Howtos  ›  Development  › 

How to detect memory leak under windows

Shulou Source: shulou.com Published: 2022-05-31 21:54:36 09月30日 Update

This article mainly introduces how to detect C/C++ memory leaks under windows related knowledge, detailed and easy to understand, simple and fast operation, with a certain reference value, I believe that everyone reading this C/C++ memory leak under windows how to detect articles will be harvested, let's take a look at it.

Detecting memory leaks

Take advantage of instrumentation provided by Visual Studio debuggers and CRT libraries (malloc and new apply)

When the program exits from only one location:

1. The following header files are required:

#define _CRTDBG_MAP_ALLOC#include#include

By including crtdbg.h, map malloc and free to_malloc_dbg and_free_dbg, respectively, for memory allocation and deallocation tracking.

The #define _CRTDBG_MAP_ALLOC statement is used to provide additional information, not absolutely necessary.

2. Before the program exits, use the following statement:

_CrtDumpMemoryLeaks();

This statement displays memory leak information in the output window.

test code

#define _CRTDBG_MAP_ALLOC#include#include#include#define NUM 10int main(){ char *test; test = (char*)malloc(NUM * sizeof(char)); _CrtDumpMemoryLeaks(); return 0;}

output result

When using_CRTDBG_MAP_ALLOC:

When_CRTDBG_MAP_ALLOC is not used:

If you add:

char *test;test = (char*)malloc(NUM * sizeof(char));

Replace with:

char* name = new char[10];

The same result will be obtained (memory location varies due to automatic allocation):

When the program exits from multiple locations:

1. Also contains the header file above

2. Include the following code at the beginning of every function that exits the program, including the main function:

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

The program automatically calls_CrtDumpMemoryLeaks(); on exit.

test code

#define _CRTDBG_MAP_ALLOC#include#include#include#define NUM 10void test1();void test2();int main(){ _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); char *test; test = (char*)malloc(NUM * sizeof(char)); int a; puts("input a number"); scanf_s("%d", &a, sizeof(int)); if (a > 10) test1(); else if(a

Tags: Memory location program detection function structure statement between code state allocation content variable knowledge result location test output information file Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Tech Info MariaDB Huawei macOS