In VS, memory leaks can be detected by using C Run-Time (CRT) libraries [1]. A typical example of enabling this feature can be like:
1 | /* the #include statements must follow the order shown here */ |
This will report the memory leaks in the Output Window as follows:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
170 bytes in 0 Free Blocks.
240 bytes in 3 Normal Blocks.
0 bytes in 0 CRT Blocks.
0 bytes in 0 Ignore Blocks.
0 bytes in 0 Client Blocks.
Largest number used: 240 bytes.
Total allocations: 240 bytes.
-----------------------------------
Detected memory leaks!
Dumping objects ->
..\test\main.cpp(29) : {415} normal block at 0x00A8FB60, 120 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
..\test\main.cpp(27) : {414} normal block at 0x00A8FAD0, 80 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
..\test\main.cpp(26) : {413} normal block at 0x00A8FA68, 40 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
Based on the memory leak report, we can easily identify where memory leaks happens (in this case, line 26/27/29) and how bad they are (e.g. leaking 120 bytes in line 29).
Note that:
- The second part of the memory leak report that contains file names and line numbers is only available after the whole application exits.
- To track memory leaks before application exit, we have to set starting and ending points in code, as we did in the above example. By moving the starting and ending points around, it is flexible for us to track the exact code that we’re focused on. Sample memory leak report can be seen from the first part of above report.
References
[1] Finding Memory Leaks Using the CRT Library: https://msdn.microsoft.com/en-us/library/x98tx3cf.aspx