title: What is wrong with this pinvoke?
body: <p>I have this piece of code that has not been modified but all of a sudden it has stopped working... I could swear that it used to work but can't guarantee it. It throws an exception:</p>
  
  <blockquote>
    <p>Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</p>
  </blockquote>
  
  <pre><code>static void Main(string[] args)
  {
      ErrorMsg(123);
  }
  
  [DllImport("kernel32.dll", EntryPoint = "FormatMessageW", CharSet = CharSet.Auto)]
  static extern int FormatMessage(int dwFlags, IntPtr lpSource, long dwMessageId, int dwLanguageId, out IntPtr MsgBuffer, int nSize, IntPtr Arguments);
  
  [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  public static extern int GetThreadLocale();
  
  /// &lt;summary&gt;
  /// Gets a Locale specific windows error
  /// code specified.
  /// &lt;/summary&gt;
  /// &lt;param name="errorcode"&gt;The errorcode.&lt;/param&gt;
  public static string ErrorMsg(long errorcode)
  {
      try
      {
          if (errorcode == 0)
              return "No Error";
          IntPtr pMessageBuffer;
          int dwBufferLength;
          string sMsg;
          int dwFormatFlags;
          //FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS
          dwFormatFlags = 0x00000100 | 0x00000200 | 0x00001000;
          dwBufferLength = FormatMessage(dwFormatFlags, IntPtr.Zero, errorcode, GetThreadLocale(), out pMessageBuffer, 0, IntPtr.Zero);
          if (dwBufferLength == 0)
              return "An Unknown Error Has occured.";
          sMsg = Marshal.PtrToStringUni(pMessageBuffer);
          Marshal.FreeHGlobal(pMessageBuffer);
          return sMsg;
      }
      catch (Exception ex)
      {
          return "An Unknown Error Has occured.";
      }
  }
  </code></pre>
  
  <p>What am I doing wrong here, I can't seem to find anything? Thanks!</p>