Should Marshal.FreeHGlobal be Called or LocalFree?

891 views Asked by At

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.

1

There are 1 answers

1
Yuval Itzchakov On BEST ANSWER

If you're unsure what one of the base class library actually does, you can always look at the source code:

public struct IntPtr : ISerializable
{
    [SecurityCritical]
    unsafe private void* m_value; // The compiler treats void* closest to uint 
                                  // hence explicit casts are required to preserve int
                                  // behavior

    public unsafe IntPtr(int value)
    {
        #if WIN32
            m_value = (void *)value;
        #else
            m_value = (void *)(long)value;
        #endif
    }
}

As you can see, this isn't actually allocating any unmanaged memory, but rather simply assigning the int to a private void*.