title: Debugging Win32 API Apps for Memory Leaks
body: <p>I was reading up on how to go about finding memory leaks with the C++ <code>new</code> operator and the standard CRT <code>malloc</code> function on a Win32 application.</p>
  
  <p>I added some stuff for working with windows sockets and I wanted to include <code>crtdbg.h</code> only if running in debug mode, along with some other defines.  So I ended up piecing this together into my <code>stdafx.cpp</code> as my standard pre-compiled header:</p>
  
  <pre><code>// stdafx.h : include file for standard system include files,
  // or project specific include files that are used frequently, but
  // are changed infrequently
  //
  
  #pragma once
  
  #include "targetver.h"
  
  #define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
  // Windows Header Files:
  #include &lt;windows.h&gt;
  
  // C RunTime Header Files
  #include &lt;stdlib.h&gt;
  #include &lt;malloc.h&gt;
  #include &lt;memory.h&gt;
  #include &lt;tchar.h&gt;
  
  // Windows Sockets
  #include &lt;winsock2.h&gt;
  #pragma comment(lib,"ws2_32.lib")
  
  
  // If running in debug mode we need to use this library to check for memory leaks, output will be in DEBGUG -&gt; WINDOWS -&gt; OUTPUT
  // http://msdn.microsoft.com/en-us/library/x98tx3cf.aspx
  #ifdef _DEBUG   
      //http://stackoverflow.com/questions/8718758/using-crtdumpmemoryleaks-to-display-data-to-console
      #ifndef DBG_NEW      
          #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )      
          #define new DBG_NEW   
      #endif
      #define _CRTDBG_MAP_ALLOC
      #include &lt;crtdbg.h&gt;
  #endif  // _DEBUG
  </code></pre>
  
  <p>I also intended to put these lines just before the exit point of my program:</p>
  
  <pre><code>#ifdef _DEBUG  
      _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );
      _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG );
      _CrtDumpMemoryLeaks(); 
  #endif
  </code></pre>
  
  <p>Anyways, it appears to compile but I get some strange warning:</p>
  
  <blockquote>
    <p>warning C4005: '_malloca': macro redefinition</p>
  </blockquote>
  
  <p>From the <code>crtdbg.h</code>.  Is this due to the wrong ordering of the headers in the <code>stdafx.h</code>, or is this normal?  Also, am I on the right track for detecting memory leaks in Win32 apps or is there something else I should be using in Visual Studio?</p>