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 thefree()from the same C RTL. And likewise on the managed side,AllocHGlobal()should be balanced byFreeHGlobal().Now,
AllocHGlobal()is implemented by calling the Win32 functionLocalAlloc. So you could free such memory with a call toLocalFreeon 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()andCoTaskMemFree(). On the managed side useMarshal.AllocCoTaskMem()andMarshal.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.