none
Memory leak in Marshal.DestroyStructure? RRS feed

  • Question

  • When testing few methods with interop, I've found a memory leak. Narrowed it down to Marshal.DestroyStructure which leaks memory. If Marshal.FreeHGlobal used instead memory does not leak. This can be tested with the code below, and watching process memory.

    Am I missing something?

    using System;
    using System.Runtime.InteropServices;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            [StructLayoutAttribute(LayoutKind.Sequential)]
            private struct TEST_STRUCT
            {
                public uint cbSize;
                public uint Fiedld1;
                public uint Fiedld2;
            }
    
            private static void TestMemoryLeak(bool useDestroyStructure)
            {
                var testStruct = new TEST_STRUCT
                {
                    cbSize = (uint)Marshal.SizeOf(typeof(TEST_STRUCT))
                };
    
                while (true)
                {
                    IntPtr pTestStruct = Marshal.AllocHGlobal(Marshal.SizeOf(testStruct));
                    Marshal.StructureToPtr(testStruct, pTestStruct, false);
    
                    if (useDestroyStructure)
                    {
                        Marshal.DestroyStructure(pTestStruct, typeof(TEST_STRUCT));  // This leaks
                    }
                    else
                    {
                        Marshal.FreeHGlobal(pTestStruct); // This does not leak
                    }
                    GC.Collect();
                }
            }
    
            static void Main(string[] args)
            {
                TestMemoryLeak(true);
            }
        }
    }
    
    


    Regards, Dmitry
    Friday, December 23, 2011 7:48 AM

Answers

All replies