I write a module in C# that exports some functions to be used in C. I need to allocate some memory for some structs to be passed between C <-> C#.
What I allocate in C I do with malloc, and in C# I do with Marshal.AllocHGlobal() (to allocate unmanaged memory to be passed to C).
Is there any problem if I free() the memory allocated with Marshal.AllocHGlobal, and if I release memory with Marshal.FreeHGlobal() which was allocated with malloc?
Thanks
The golden rule is that you must deallocate from the same heap that was used to allocate the memory.
If you allocate it with malloc()
, you must deallocate it with the free()
from the same C RTL. And likewise on the managed side, AllocHGlobal()
should be balanced by FreeHGlobal()
.
Now, AllocHGlobal()
is implemented by calling the Win32 function LocalAlloc
. So you could free such memory with a call to LocalFree
on the native side. And vice versa.
If you want to use a heap that is shared between native and managed, it is more common to use the COM heap. On the native side use CoTaskMemAlloc()
and CoTaskMemFree()
. On the managed side use Marshal.AllocCoTaskMem()
and Marshal.FreeCoTaskMem()
.
However, you should avoid designing the system like this. It is much simpler to stick to a rule that all memory allocated in the managed side is deallocated there, and likewise for the native side. If you don't follow that rule you will likely soon lose track of who is responsible for what.
There might or might not be a problem - this is totally implementation-dependant. Never rely on an implementation detail for your app functionality!
So I recommend not to use Marshal.AllocHGlobal()
, malloc()
, Marshal.FreeHGlobal()
and free()
crosswise.
One example, where you will run into dire trouble is if you use a library, that does some sort of fancy malloc()/free()
magic - you might even not know that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With