1

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.

Community
  • 1
  • 1
AshesToAshes
  • 937
  • 3
  • 14
  • 31
  • 3
    There's no memory allocation, so there's nothing to free. It's not clear to me what you think your line of code does. Can you explain what it does? –  Nov 30 '14 at 10:48
  • Aha OK I thought that might be the case. I've received this code from someone else, so trying to work out what buf is being used for as it is passed into a parameter to a 3rd party C++ API. – AshesToAshes Nov 30 '14 at 10:55

1 Answers1

1

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*.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321