is it okay for native code to call calloc in c# app?

  • Thread starter Thread starter Yostage
  • Start date Start date
Y

Yostage

I'm calling a function in a DLL from my C# app. The function returns a
int* that it allocates using calloc.
Will this be a memory leak problem for my app?
Is there a way to fix it other than adding another method to the DLL
which frees the memory?

thanks!
 
Yostage,

Yes, this will be a problem. Generally speaking, you can not depend on
memory management routines to be the same between programs. For example, if
you allocate memory with calloc in your program, the implementation of
corresponding free mechanism might not be the same, and you will end up with
problems all over the place.

The best way to handle this would be to have the function accept a
pointer with a pre-allocated buffer of memory, which your function then
populates.

The only mechanism that is guaranteed to work for allocating and freeing
memory between disparate programs (as far as I know) is the COM memory
manager (IMalloc interface). In your C++ code, you can call CoTaskMemAlloc
and return a memory buffer allocated with that. Then, the calling code can
call CoTaskMemFree (or in .NET, the static FreeCoTaskMem method on the
Marshal class).

Hope this helps.
 
If you use platform invoke framework GC can't do anything with memory
allocated inside non-Net assemblies. So I would suggest to implement
analogue of Dispose in your dll.

HTH
Alex
 
Back
Top