Let's say I have a managed C# test application that is used to test a native C/C++ API. Now I am suspecting that there is a memory leak somewhere in the C/C++ code. What I need to do is be able to calculate the amount of memory that is allocated by the native code. It doesn't need to be super accurate, but being able to see whether this value is going up or not based on different tests I'm running on the native code would be helpful.
I tried calling GC.GetTotalMemory(true), but the value it returns is substantially lower than the value shown for the process in task manager. I suspect the value returned by GetTotalMemory is just for your managed application, while task manager shows total .Net VM memory.
Does anyone know of a good way to do this?
WinDbg, call your API in a tight loop and confirm it is responsible for the leak, better yet call your native API from native, you could have your leak at the marshalling layer. If the memory footprint increments linearly, find the source of the leak. You can look at the heaps and then identify the objects taking the most of it, see the documentation for !heap. Alternatively, a classic technique is to track allocations by overriding new/delete. Don't know of any other ways to do it. There's tool that can automate some of this, Visual Studio has one too I believe, but that's just uncool in my book. Use WinDbg.
BTW, if you have leaks in native code you used C++ very inappropriately
Thanks for the suggestions, I'll try some of those. The code I'm testing is a large C API written in C/C++. I did not write 98% of the code so yea I can't vouch for it being "appropriate" in all cases
Basically all I need to do is find a reliable way to tell the total amount of memory used by the native code. This way I can tell whether the native memory usage is going up or not over time, and whether a certain code fix resolved the remaining memory leaks.
From what I can tell, it appears I fixed the last of the memory leaks yesterday, so this may not be such a big issue at this point. Still for academic and future purposes I would like to know of a reliable way to measure memory used by the unmanaged code.
BTW this is the only thing I found that a managed test driver is not good at. The C# test application I'm using is quite complex and if I needed to write it in C/C++ it would not have been anywhere close as feature-rich and easy to maintain/expand as it is now.
Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.