0

If a dynamic array is allocated with

intPtr = new int[1234];

in c++ and the data is subsequently marshaled to a managed C# array, is it valid to free the originally allocated memory on the managed side using

Marshal.FreeHGlobal()

or will this leak memory?

If this does leak memory, is there another method that can be used on the managed side to cleanly free the memory or is it necessary to implement the freeing code on the native side and pass a callback function to the managed side?

Thanks!

matthias_buehlmann
  • 4,641
  • 6
  • 34
  • 76
  • Short answer: you'll only do damage and won't free anything. You'll need to free the memory C++ side. – xanatos Apr 04 '17 at 08:55
  • See for example: http://stackoverflow.com/a/29077711/613130, http://stackoverflow.com/a/18172997/613130 – xanatos Apr 04 '17 at 08:56
  • Apples and oranges. Memory that was allocated via `new` in c++ Windows has nothing to do with the `GlobalFree/Heapxxxxx` functions in the Win32 API. You shouldn't even mix the two on the c/c++ side. http://stackoverflow.com/a/34326909/585968 –  Apr 04 '17 at 09:17

1 Answers1

1

You can't call free/delete from C#. You have to do it C/C++ side (the new/malloc by default use a "private" C/C++ allocator). The correct way to do it is to expose a Free(IntPtr) method in the C/C++ library, OR only use a shared allocator (but note that if you want the C++ destructor to be called on freeing of the memory, then you have to do the delete in C++)

Clearly in C/C++ you can use LocalAlloc to allocate memory and then in C# you can use Marshal.FreeHGlobal(), but then we are in the OR only use a shared allocator case (and you still have the problem that you can't call the C++ destructor from C#)

xanatos
  • 109,618
  • 12
  • 197
  • 280