1

I am using Visual Studio 2013, and taking a course in C programming and we started talking about memory bugs detaction, in particular memory leaks, and how to detect them using Valgrind on Linux.

I want to know if there is a way to detect such memory leaks using VS 2013. I tried searching online but it just leads to lots of articles and blogs and msdn posts and blogs with lots of words like dump files, and analizing them, etc which weird because:

1) It sounds so complex, convoluted and unintuitive it is actually hard to comprehend it.

2) The main reason this is weird is due to the fact that VS is the most advanced IDE around and Microsoft spends so much money on in, yet from what I have read it seems that there is no simple way to use VS to detect memory leaks - certainly no way that's as simple as Valgrind where I only have to compile the program and run the command
valgrind -leaks-check=yes ProgramName

and it simply prints to me all location it thinks there is a memory leak and describes the error (like not freeing memory after allocating it with malloc hence having "dead" memory after the program finishes, or accessing memory that's out of the array bounds)

So my question is how to use VS 2013 in order to achieve the same results and to find out First in high level if there are memory leaks in the program, and second - to detect in a simple manner where those leaks are- preferably without involving dump files (not that I know how to use them anyway in VS).

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
scifie
  • 65
  • 1
  • 2
  • 14
  • Actually, there are 2 levels on which you can detect memory leaks (or 3, depending on how you count). First off, you can use the static code analyzer built in with VS2013 (even with the free community edition). Second, you can do debug build and use runtime checks to your benefit. Last not least, there is a set of functions in the windows API which allows checking heap and finding out if you have for example a corrupted heap, dangling heap objects, ... Probably your best weapon against leaks is to switch to c++ and write code not using direct memory allocations in the first place. – BitTickler Apr 16 '15 at 23:35
  • 1
    [Visual Leak Detector](https://vld.codeplex.com/) – Axalo Apr 16 '15 at 23:40
  • Use 3rd party tool: VLD, Deleaker and so on. – Artem Razin Apr 17 '15 at 08:39
  • Actually those tools do the same as the normal heap diagnostic functions do, wrapping the result in a candy UI. Why use a tool to replace 6-10 lines of instrumentation code? – BitTickler Apr 17 '15 at 16:58
  • @user2225104 I have a few things I'd like you to clarify/eleborate regarding your first comment (keep in mind that I have never done memory profiling until now so I am unfamiliar with said tools): 1) What is static code analyzer in VS and how to use it (where is it located in the UI) and what does it do- can it indicate for example that I have dangling objects for example? 2) What do you mean by using runtime checks - do you mean running the code step by step? That can't locate memory leaks 3) What functions and APIs are you talking about and more practically - how and where do I use them? – scifie Apr 17 '15 at 21:46
  • Main menu item "analyze" and below. Documentation is a bit sparse on what it finds but hey - ask the same about lint or other static code checkers and you will get similar answers. As for the other questions of yours I would indeed need to write a full fledged answer... hm... – BitTickler Apr 17 '15 at 23:30
  • You can use [visual-leak-detector](http://stackoverflow.com/questions/33180597/visual-leak-detector-not-finding-leaks-vs2013/33182833#33182833). look at my answer for VS2013 – HDJEMAI Nov 04 '15 at 06:38
  • also dr memory.. – pm100 Oct 18 '22 at 22:22

1 Answers1

0

The answer I offer cannot be perfect as exhaustively explaining ALL features VS2013 etc. offer to find C/C++ heap hickups could be a book well sold. And not a very thin one for that matter.

First, things I will NOT cover:

  • sal.h - Semantic annotations (which are also used by MS tools, if provided).
  • Not EVERY _Crt* function available. Only a few to give the idea.
  • Additional steps an application designer might to add to their design for a "production quality" code base.

Having said that, here a piece of annotated code containing various bugs. Each bug is annotated with how it was possible to detect it by means of what VS2013 has to offer. Either at run time or at compile time or with static code analysis.

The compile time error sections are placed in comments, btw.

#include "stdafx.h"
#include <crtdbg.h>
#include <malloc.h>
#include <cstdint>
#include <cstdlib>

// This small helper class shows the _Crt functions (some of them)
// and keeps the other code less cluttered. 
// Note: This is NOT what you should do in production code,
// as all those _Crt functions disappear in a release build,
// but this class does not disappear...
class HeapNeutralSection
{
    _CrtMemState m_start;

public:
    HeapNeutralSection()
    {
        _CrtMemCheckpoint(&m_start);
    }

    ~HeapNeutralSection()
    {
        _CrtMemState now;
        _CrtMemState delta;
        _CrtMemCheckpoint(&now);
        if (_CrtMemDifference(&delta, &m_start, &now))
        {
            // This code section is not heap neutral!
            _CrtMemDumpStatistics(&delta);
            _CrtDumpMemoryLeaks();
            _ASSERTE(false);

        }
    }
};


static void DoubleAllocationBug()
{
    {
        HeapNeutralSection hns;

        uint32_t *rogue = (uint32_t*)malloc(sizeof(uint32_t));
        if (NULL != rogue)
        {
            *rogue = 42; // Static Analysis without the NULL check: Dereferencing null pointer.
        }
        rogue = (uint32_t*)malloc(sizeof(uint32_t));
        free(rogue);
        // detected in destructor of HeapNeutralSection.
    }
}

static void UninitializedPointerAccessBug()
{
//  uint32_t *rogue;
//  *rogue = 42; // C4700: uninitialized local variable 'rogue' used.
}

static void LeakBug()
{
    {
        HeapNeutralSection hns;

        uint32_t *rogue = (uint32_t*)malloc(sizeof(uint32_t));
        if (NULL != rogue)
        {
            *rogue = 42; // Static Analysis without the NULL check: Dereferencing null pointer.
        }
    }
}

static void InvalidPointerBug()
{
    // Not sure if the C-compiler also finds this... one more reason to program C with C++ compiler ;)
    // uint32_t *rogue = 234; // C2440: 'initalizing': cannot convert from 'int' to 'uint32_t *'

}

static void WriteOutOfRangeBug()
{
    {
        HeapNeutralSection hns;
        uint32_t * rogue = (uint32_t*)malloc(sizeof(uint32_t));
        if (NULL != rogue)
        {
            rogue[1] = 42; // Static analysis: warning C6200: Index '1' is out of valid index range '0' to '0' for non-stack buffer 'rogue'.
            rogue[2] = 43; // Static analysis: warning C6200: Index '2' is out of valid index range '0' to '0' for non-stack buffer 'rogue'.
            // warning C6386: Buffer overrun while writing to 'rogue':  the writable size is '4' bytes, but '8' bytes might be written.
        }
        free(rogue); // We corrupted heap before. Next malloc/free should trigger a report.
        /*
        HEAP[ListAppend.exe]: Heap block at 0076CF20 modified at 0076CF50 past requested size of 28
        ListAppend.exe has triggered a breakpoint.
        */
    }
}

static void AccessAlreadyFreedMemoryBug()
{
    {
        HeapNeutralSection hns;
        uint32_t * rogue = (uint32_t*)malloc(sizeof(uint32_t));
        free(rogue);

        *rogue = 42; // Static analysis: warning C6001: Using uninitialized memory 'rogue'.
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    // checks heap integrity each time a heap allocation is caused. Slow but useful.
    _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF); 

    AccessAlreadyFreedMemoryBug();
    WriteOutOfRangeBug();
    UninitializedPointerAccessBug();
    DoubleAllocationBug();

    // _CrtDumpMemoryLeaks();
    return 0;
}

Last not least, on Windows CE and in the DDKs (maybe also in the platform SDKs), there used to be the 2 static code checkers "prefast" and "prefix". But maybe they are now outdated.
Additionally, there are MS research projects, going a step beyond sal.h, such as: VCC, which help finding concurrency bugs etc.

miken32
  • 42,008
  • 16
  • 111
  • 154
BitTickler
  • 10,905
  • 5
  • 32
  • 53