65

In Linux, I have been using valgrind for checking if there are memory leaks in an application. What is the equivalent in Windows? Can this be done with Visual Studio 2010?

participant
  • 2,923
  • 2
  • 23
  • 40
softwarematter
  • 28,015
  • 64
  • 169
  • 263
  • possible duplicate of [Is there a good Valgrind substitute for Windows?](http://stackoverflow.com/questions/413477/is-there-a-good-valgrind-substitute-for-windows) – Patrick Jan 25 '11 at 11:16

9 Answers9

80

Visual Studio 2019 has a decent memory analysis tool, it may be used interactively while debugging or by programming (without debugging), I show a minimal example in both cases in the following.

The main idea is to take a snapshot of the heap at the beginning and at the end of the process, then to compare the states of memory to detect potential memory leaks.

Interactively

Create the following main.cpp file (in a new console application) :

#include <string.h>
int main()
{
 int a = 1;
 char* s = new char[17];
 strcpy_s(s,17,"stackoverflow_pb");
 char* ss = new char[14];
 strcpy_s(ss, 14,"stackoverflow");
 delete[] ss;
 return 0;
}

Then :

  1. Put a breakpoint on the first line "int a..."
  2. Click Debug > Windows > Show Diagnostic Tools; and pick memory usage
  3. Then debug the code (F5), when the breakpoint is hit, click Take snapshot on the Memory Usage summary toolbar.
  4. Go to the last line "return 0.." (step over (F10) several times) and take another snapshot.
  5. Click on the red arrow in the second snapshot (in memory usage tab)
  6. this will open a new "snapshot" tab that permits you to compare this snapshot with the first one (or another one) and to detect memory leaks. In this example there is a memory leak for variable s (stackoverflow_pb). You can find it by double click the "char[]" object.

The key steps of the above procedure are shown in the following image:

memory analysis interactively

By programming

Replace the code with the following:

#include <iostream>

#include "windows.h"
#define _CRTDBG_MAP_ALLOC //to get more details
#include <stdlib.h>  
#include <crtdbg.h>   //for malloc and free
int main()
{
    _CrtMemState sOld;
    _CrtMemState sNew;
    _CrtMemState sDiff;
    _CrtMemCheckpoint(&sOld); //take a snapshot
    char* s = new char[17];
    strcpy_s(s, 17, "stackoverflow_pb");
    char* ss = new char[14];
    strcpy_s(ss, 14, "stackoverflow");
    delete[] ss;
    _CrtMemCheckpoint(&sNew); //take a snapshot 
    if (_CrtMemDifference(&sDiff, &sOld, &sNew)) // if there is a difference
    {
        OutputDebugString(L"-----------_CrtMemDumpStatistics ---------");
        _CrtMemDumpStatistics(&sDiff);
        OutputDebugString(L"-----------_CrtMemDumpAllObjectsSince ---------");
        _CrtMemDumpAllObjectsSince(&sOld);
        OutputDebugString(L"-----------_CrtDumpMemoryLeaks ---------");
        _CrtDumpMemoryLeaks();
    }
    return 0;
}

It does the same thing but by code, so you can integrate it in an automatic build system, the functions _CrtMemCheckpoint take the snapshots and _CrtMemDifference compare the memory states of snapshot and returns true is they are different.

Since it is the case, it enters the conditional block and prints details about the leaks via several functions (see _CrtMemDumpStatistics , _CrtMemDumpAllObjectsSince and _CrtDumpMemoryLeaks - the latter doesn't require snapshots).

To see the output, put a break point in the last line "return 0", hit F5 and look at the debug console. Here is the output :

enter image description here


To get more information, see the following links :

UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
Malick
  • 6,252
  • 2
  • 46
  • 59
  • This is very good. Is there a way we can check for 1. mixing array `new[]` and the wrong `delete`, 2. accessing freed memory, 3. other ways of corrupting memory like out of bound access and such. 4. Accessing uninitialized memory – Aykhan Hagverdili Mar 11 '20 at 15:16
  • 1
    Sorry I don't know for 1,3 and 4 but I would use a static analysis tool for it. Regarding 2 (accessing freed memory) you can use the `_CRTDBG_DELAY_FREE_MEM_DF` flag (see the above link "CRT debug Heap Files"). – Malick Mar 11 '20 at 18:54
  • Thanks. `OutputDebugStringW` required for `LPCWSTR`, (3 characters not enough for an edit as the rest of the answer is perfect!) – Laurie Stearn Aug 08 '20 at 14:00
  • `/fsanitize=address` can now be used with x64 and x86 for similar memory problems. [AddressSanitizer](https://learn.microsoft.com/en-us/cpp/sanitizers/asan?view=msvc-160#:~:text=Use%20the%20AddressSanitizer%20in%20Visual%20Studio,-AddressSanitizer%20is%20integrated&text=In%20the%20Property%20Pages%20dialog,OK%20to%20save%20your%20changes.) – Aykhan Hagverdili May 26 '21 at 21:46
  • 1
    This is 1000% too much work. Is there really no Windows valgrind equivalent? – Roflcopter4 Mar 01 '22 at 22:31
  • @Roflcopter4 not really. Your best bet might be to develop on Linux with Valgrind and make sure it's portable enough to also compile on Windows. – Aykhan Hagverdili Mar 27 '22 at 16:16
  • Came here because `_CRTDBG_MAP_ALLOC` isn't giving me file/line info (VS 2019) as indicated in the help pages. I unfortunately see the same issue in the screenshot above. – Adversus Oct 18 '22 at 09:58
  • @LaurieStearn does AddressSanitizer works in VS2010 ultimate (windows)? – Zrn-dev Dec 01 '22 at 06:10
  • @Zm_dev: Ayxan Haqverdili is sure to know the answer. (cannot ref more than user in comment, sorry). – Laurie Stearn Dec 01 '22 at 08:51
  • if I were to use the programming method, but wanted to see the results in the output debug window.. is it fine if I just run the program as normal for a while (minutes, hours) then attach to it and quit the program while attached? the dump info should then be for the entire time the program was running? or just while it was attached? – ycomp Jan 05 '23 at 22:26
  • This only works if you know there is a leak in the first place and is actively looking for it. I know you can use _CrtSetDbgFlag(...) but I wish there is just a toggle button in Visual Studio instead of needing to pasting _CrtXYZ(...) call in every time. – stackoverblown Jun 30 '23 at 10:03
13

How about Visual Leak Detector? It's not inbuild, but I do think it's the most popular one.

default
  • 11,485
  • 9
  • 66
  • 102
  • 7
    Has since moved to https://kinddragon.github.io/vld/, and then was apparently abandoned in 2017. – Nic Sep 05 '19 at 14:02
  • 3
    Still seems to work with VS 2019, see here: https://stackoverflow.com/questions/58439722/how-to-install-visual-leak-detector-on-visual-studio-2019 – FourtyTwo Mar 10 '20 at 12:25
4

Dr. Memory is a memory monitoring tool capable of identifying memory-related programming errors such as accesses of uninitialized memory, accesses to unaddressable memory (including outside of allocated heap units and heap underflow and overflow), accesses to freed memory, double frees, memory leaks, and (on Windows) handle leaks, GDI API usage errors, and accesses to un-reserved thread local storage slots.

Dr. Memory operates on unmodified application binaries running on Windows, Linux, Mac, or Android on commodity IA-32, AMD64, and ARM hardware.

Dr. Memory is built on the DynamoRIO dynamic instrumentation tool platform.

AntonK
  • 1,210
  • 1
  • 16
  • 22
3

C++ Memory Validator finds memory and handle leaks in native Windows programs built with Visual Studio, Delphi and other compilers. Fast and can handle large workloads (some users track several billion allocations and deallocations in one run).

Disclosure: I'm the designer of C++ Memory Validator. We built it because other tools couldn't handle the workload when we were working with SolidWorks R&D Ltd.

Stephen Kellett
  • 3,078
  • 1
  • 22
  • 25
3

Visual Studio 2015 and later versions have Native Memory Leak Diagnostic Tool, check this for details: https://dzone.com/articles/native-memory-leak-diagnostics.

3

Application Verifier is a good tool for detecting leaks in native (C or C++) application. You can use it along with Visual studio or WinDbg . Apart from memory leaks, you can check for heap corruptions, invalid handle usage as well. Using application verifier along with WinDbg (!analyze -v) provides good insights.

Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
nkvns
  • 580
  • 3
  • 5
1

A reliable solution is to use the Address Sanitizer for visual studio. This is a cross platform / cross compiler solution so the knowledge you gain will be transferable to gcc and clang.

This tool has extensions for thread sanitization, and general memory error detection (use after free, double free, uninitialized use etc) but leak detection is one of its strong points. You need the /fsanitize=address /Zi options for the Microsoft compiler, but you can refer on the first linked article on how to incorporate it on solutions and bigger projects (either through CMake configurations, or project properties tweaking)

Lorah Attkins
  • 5,331
  • 3
  • 29
  • 63
0

You can use DevPartner tool for finding memory leaks in C++ applications using visual studio.

ckv
  • 10,539
  • 20
  • 100
  • 144
0

A standalone tool (CLI) for tracking native (C++) memory leaks. Run your app in Release mode (PDBs should be available) and let it run along with it. It outputs all the suspected call stacks and their respected leak size:

GitHub: C++ Memory Leak Detector for Windows

user1595443
  • 205
  • 3
  • 10