Search code examples
c#marshallingunmanaged-memory

How Marshal.FreeHGlobal can free unmanned array?


I have reserved an unmanned array using:

IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(array[0]) * array.Length);

then free it using:

Marshal.FreeHGlobal(ptr );

as far as I read, this will free the memory correctly and no memory leak gonna happen. My question: is this true? if it is, how that works? is the Marshal state-full and store meta-data about every reserved data?


Solution

  • The AllocHGlobal method exposes the LocalAlloc function. And the FreeHGlobal Method exposes the LocalFree function. The memory management is not being done by any managed component. It is done by the code behind these windows api functions.

    To answer your question: Yes it has to keep track of the allocated size. You can retrieve the size of a handle by calling LocalSize function. To be honest, I don't know how its being done internally, but you don't need to know that.