I'm having problems with a slow memory leak in my mixed mode C++/CLR .NET application.
(It's C++ native static libraries linked into a VS2008 C++/CLR Windows Forms app with the "/clr" compiler setting)
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.
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").
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).
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.
The .NET image reports that it is using around 1.5 MB of memory (from perfmon).
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.
So basically what I'm trying to get across here is that I don't think any of the native code is leaking memory.
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): http://support.microsoft.com/kb/961870
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).
Anyone have any suggestions?
A few things that might help me:
Thanks for any help
John
OK I finally found the problem.
It was caused by an incorrect setting for /EH (Exception Handling).
Basically, with mixed mode .NET apps, you need to make sure all statically linked libs are compiled with /EHa instead of the default /EHs.
(The app itself must also be compiled with /EHa, but this is a given - the compiler will report error if you don't use it . The problem is when you link in other static native libs.)
The problem is that exceptions caught in the managed bit of the app, which were thrown within native libraries compiled with /EHs end up not handling the exception correctly. Destructors for C++ objects are not then called correctly.
In my case, this only occurred in a rare place, hence why it took me ages to spot.