Fixes bugs in String marshalling.
authorFraser Waters <frassle@gmail.com>
Thu, 19 Jun 2014 21:51:47 +0000 (22:51 +0100)
committerFraser Waters <frassle@gmail.com>
Thu, 19 Jun 2014 21:51:47 +0000 (22:51 +0100)
Fixes two issues:
1. FreeStringArrayPtr used the wrong variable in the offset to
ReadIntPtr causing an access violation.
2. Better cleanup of memory in MarshalStringArrayToPtr when any alloc
fails.

Source/OpenTK/BindingsBase.cs

index a12c7a6..7ea697f 100644 (file)
@@ -202,10 +202,25 @@ namespace OpenTK
                     throw new OutOfMemoryException();
                 }
 
-                for (int i = 0; i < str_array.Length; i++)
+                int i = 0;
+                try
                 {
-                    IntPtr str = MarshalStringToPtr(str_array[i]);
-                    Marshal.WriteIntPtr(ptr, i * IntPtr.Size, str);
+                    for (i = 0; i < str_array.Length; i++)
+                    {
+                        IntPtr str = MarshalStringToPtr(str_array[i]);
+                        Marshal.WriteIntPtr(ptr, i * IntPtr.Size, str);
+                    }
+                }
+                catch (OutOfMemoryException oom)
+                {
+                    for (i = i - 1; i >= 0; --i)
+                    {
+                        Marshal.FreeHGlobal(Marshal.ReadIntPtr(ptr, i * IntPtr.Size));
+                    }
+
+                    Marshal.FreeHGlobal(ptr);
+
+                    throw oom;
                 }
             }
             return ptr;
@@ -220,7 +235,7 @@ namespace OpenTK
         {
             for (int i = 0; i < length; i++)
             {
-                Marshal.FreeHGlobal(Marshal.ReadIntPtr(ptr, length * IntPtr.Size));
+                Marshal.FreeHGlobal(Marshal.ReadIntPtr(ptr, i * IntPtr.Size));
             }
             Marshal.FreeHGlobal(ptr);
         }