title: Memory leak in Mixed Mode C++/CLR application
body: <p>I'm having problems with a slow memory leak in my mixed mode C++/CLR .NET application.</p>
  
  <p>(It's C++ native static libraries linked into a VS2008 C++/CLR Windows Forms app with the "/clr" compiler setting)</p>
  
  <p>Typical behaviour: app starts using 30 MB (private memory). Then leaks memory slowish, say a MB every hour when running under simulated heavy load. This simulates the app being live for days or weeks.</p>
  
  <p>I've tried using several tools to track down memory leaks including both the CRT debugging stuff that comes with the Visual Studio CRT libs. I've also used a commercial leak detection tool ("Memory Validator"). </p>
  
  <p>Both report negligible memory leaks at shutdown (a few minor entries that amount to a few KB that I'm not worried about). Also, I can see when running that the tracked memory doesn't seem to amount to that much (so I don't believe it is just memory that is being held and only released at app exit). I get around 5 MB of listed memory (out of total > 30MB).</p>
  
  <p>The tool (Memory Validator) is setup to track all memory usage (including malloc, new, Virtual memory allocation and a whole bunch of other types of memory allocation). Basically, every setting for which memory to track has been selected.</p>
  
  <p>The .NET image reports that it is using around 1.5 MB of memory (from perfmon).</p>
  
  <p>Here's a final bit of information: we have a version of the app which runs as a native console application (purely native - not CLR at all). This is 95% the same as the mixed mode except without the UI stuff. This doesn't seem to leak memory at all, and peaks at around 5MB private bytes.</p>
  
  <p>So basically what I'm trying to get across here is that I don't think any of the native code is leaking memory.</p>
  
  <p>Another piece of the puzzle: I found this which refers to memory leaks in mixed mode applications when targeting 2.0 framework (which I am): <a href="http://support.microsoft.com/kb/961870" rel="noreferrer">http://support.microsoft.com/kb/961870</a></p>
  
  <p>Unfortunately the details are infuriatingly sparse so I'm not sure if it's relevant. I did try targeting 3.5 framework instead of 2.0 but still had the same problem (maybe I didn't do this right).</p>
  
  <p>Anyone have any suggestions?</p>
  
  <p>A few things that might help me:</p>
  
  <ul>
  <li>Are there any other kind of memory allocations that I'm not tracking?</li>
  <li>How come the figures don't add up? I get 5 MB of CRT memory usage, 1.5 MB of .NET memory so how come the whole app uses 30MB private bytes? Is that all tied up in the .NET framework? Why don't I see these in the leak tool? Won't the .NET framework appear as some kind of allocated memory? </li>
  <li>Any other leak detection tools which work well with mixed mode apps?</li>
  </ul>
  
  <p>Thanks for any help</p>
  
  <p>John</p>