Skip to content

Commit 74e3a74

Browse files
douglas-piconiUnityAlex
authored andcommitted
Avoid using StringBuilder marshalling which leaks memory on Win32 (case 1211367).
1 parent d3a32ba commit 74e3a74

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

mcs/class/System/ReferenceSources/Win32Exception.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,24 @@ partial class Win32Exception
1111
#if !MOBILE
1212
[DllImport ("Kernel32", CharSet = CharSet.Unicode)]
1313
static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId,
14-
[Out] StringBuilder lpBuffer, int nSize, IntPtr[] arguments);
14+
[Out] char[] lpBuffer, int nSize, IntPtr[] arguments);
15+
16+
const int MAX_MESSAGE_LENGTH = 256;
1517
#endif
1618

1719
internal static string GetErrorMessage (int error)
1820
{
1921
#if !MOBILE
2022
if (Environment.IsRunningOnWindows) {
21-
StringBuilder sb = new StringBuilder (256);
23+
char[] messageArray = new char[MAX_MESSAGE_LENGTH];
2224

2325
int result = FormatMessage (0x1200 /* FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM */,
24-
IntPtr.Zero, (uint)error, 0, sb, sb.Capacity, null);
26+
IntPtr.Zero, (uint)error, 0, messageArray, MAX_MESSAGE_LENGTH, null);
2527

2628
if (result == 0)
2729
return "Error looking up error string";
2830

29-
return sb.ToString ();
31+
return new string(messageArray);
3032
}
3133
#endif
3234

0 commit comments

Comments
 (0)