Seen a piece of code which I'm not sure whether I need to release memory. If I have this block below:
IntPtr buf = new IntPtr(logRecord.ToInt32() + logTotalCount *
Marshal.SizeOf(typeof(SomeUnmanagedStruct)));
Do I need to call Marshal.FreeHGlobal(buf)
?
From my limited understanding (and from this SO), I don't think we should call FreeHGlobal
as we are not calling Marshal.AllocHGlobal
. However, I have also read from this SO that LocalFree
may need to be called?
Any advise what is the correct way to free this memory (if I need to do anything at all)?
UPDATE: Just in case anyone is interested in a IDISPOSABLE wrapper class, there is a great article here.
If you're unsure what one of the base class library actually does, you can always look at the source code:
As you can see, this isn't actually allocating any unmanaged memory, but rather simply assigning the
int
to a privatevoid*
.