I’m writing some native C++ code which needs to be called from C# (and I can’t replace the C++ native code with C# code).
I found memory corruptions while allocating/deallocating some memory in the native C++ code using malloc/free. Then I used LocalAlloc/LocalFree and HeapAlloc/HeapFree and had the same problems.
The allocations/deallocations seem to be correct, and they happen in a separate thread, created by the native code.
I was wondering which is the best allocation strategy to use in a native C++ library called by C#
EDIT: found the problem: the problem wasn’t in the allocation/deallocation code, but in some memory being written after being deallocated.
As long as the C# side of the code uses the compiler’s
/unsafeswitch and thefixedkeyword used for holding the buffer of data, I think you should be ok.As to the question of your memory allocation, it may not be the C++ memory allocation code that is causing the problem, it could be the way how the C++ code is interacting with the driver…maybe using
VirtualAlloc/VirtualFreepair as per the MSDN docs…Edit: When you try to allocate the buffer to hold the data from the C++ side after interacting with the driver…possibly a race-condition or interrupt latency is causing a memory corruption…just a thought…
Hope this helps,
Best regards,
Tom.