none
Attempted to read or write protected memory

    Question

  • Some users get this error , from time to time: "Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt"

    My application is compiled for .NET framework 3.5

    The error occurs (it doesn't happen all the time) when it's loading a image from disk to clipboard in order to paste it into a richtextbox  . Can this cause the problem? 

    Monday, August 15, 2011 1:43 PM

Answers

  • Hi FAndrei

    Welcome to MSDN Forum.

    "Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt

    This issue shouldn't happen in managed code. You can try setting Visual Studio Debugger to bypass this exception:

    Tools menu ->Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load"

     

    Also you can check this case about some instruction, which discussed the similar issue to yours.

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/6adca20b-649f-41a4-8fa1-09534882d76c

    I have debugged similar problems in the past and it can be very frustrating. The problem is typically caused by some component (typically unmanaged, but can also be a bad P/Invoke signature) that corrupts the program's memory. You often see differences between debug and release builds because debug builds contain extra metadata to assist in debugging. In debug mode, the corruption will kill some debug metadata, which will only cause you to see spurious debugging information, but not cause the program to crash. In release, the debug data is not present and the error overwrites critical data such as return addresses, which will cause the program to crash. You will also see small changes (like changing compiler optimizations, or re-ordering instructions) cause code to start working. What you've done is mask the problem. The memory corruption is still occuring, it's just not occuring to a critical piece of memory such as a return address. You will likely see it re-appear later as you continue modifying the code.

    This is honestly a brutal class of problems to diagnose because they're only present when you don't have debug information. Some suggestions:

    1.   Try turning on all optimizations, run the program under the debugger, and see if the error occurs. (Typically all optimizations are turned off in debug mode so that debugging is easier.) This will at least give you a way to reproduce the error when you have more debug information. This honestly won't help you a whole lot because by the time you crash, the method call that corrupted the memory is long gone.

    2.   Look at all unmanaged code that you're calling: COM objects, C/C++ DLLs, Win32 calls, etc. Check the P/Invoke signatures and COM interop thunks for all unmanaged code to verify that they're correct. Don't trust P/Invoke signatures that you find on the 'net. They're not always correct. Verify for yourself that your data types and parameter orderings are correct.

    3.   Try removing the unmanaged code (stub out the calls) and see if the problem goes away. If it does, investigate the component to verify that it is free of memory leaks. (Note that you might only be masking the problem as you re-arrange code.)

    4.   Try running your code under a unmanaged memory checker like Compuware BoundsChecker, which will look for memory leaks and access violations. This will likely give you some hints as to which unmanaged component is misbehaving.

     


    Martin Xie [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, August 19, 2011 6:06 AM
    Moderator

All replies

  • Do you know what line of code you get this exception on?
    Monday, August 15, 2011 2:10 PM
    Moderator
  • I don't know. I didn't get the error in a while (over 2 weeks) and I don't know the exact line .

     

    Last time i did, I got a  "Division by zero exception" somewhere in the following function and right after that, when I pressed continue , "Attempted to read or write protected memory" and the application crashed . 


    It's mainly a chat application . This function inserts emoticons in the richtextbox :

     

     

       public void insert_emoticons(String msg)
        {
          int nr = 0;
          Object clip = new Object();
          try
          {
            if (Clipboard.ContainsAudio())
            {
              clip = Clipboard.GetAudioStream();
              nr = 1;
            }
            else if (Clipboard.ContainsFileDropList())
            {
              clip = Clipboard.GetFileDropList();
              nr = 2;
            }
            else if (Clipboard.ContainsImage())
            {
              clip = Clipboard.GetImage();
              nr = 3;
            }
            else if (Clipboard.ContainsText())
            {
              clip = Clipboard.GetText();
              nr = 4;
            }
          }
          catch (System.Exception ex)
          {
            rtberror.AppendText("EX insert_emoticons getclipboard" + ex.ToString());
          }
    
          try
          {
    
            int inserate = 0;
            richTextBox2.ReadOnly = false;
            int ini;
            for (int i = 0; i <= msg.Length - 1; i++)
            {
              ini = i;
              if (i < msg.Length - 1)
                if (Convert.ToString(msg[i]).Equals(":"))
                {
    
                  if (Convert.ToString(msg[i + 1]).Equals("D", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("exciting-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("P", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("grimace-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals(")", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("big-smile-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("A", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("anger-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("B", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("bad-egg-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("C", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("beaten-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("D", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("black-heart-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("(", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("cry-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("E", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("electric-shock-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("F", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("eyes-droped-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("G", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("girl-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("H", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("greedy-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("I", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("haha-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("J", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("happy-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("K", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("horror-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("L", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("money-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("N", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("nothing-to-say-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("X", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("red-heart-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("M", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("scorn-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("O", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("shocked-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("Q", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("secret-smile-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("R", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("shame-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("S", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("super-man-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("U", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("unhappy-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("V", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("victory-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("w", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("what-icon.bmp");
                    inserate++;
                    i++;
                  }
                  else if (Convert.ToString(msg[i + 1]).Equals("|", StringComparison.OrdinalIgnoreCase))
                  {
                    if (inserate <= 3)
                      insertimage("amazing-icon.bmp");
                    inserate++;
                    i++;
                  }
    
                  if (ini == i)
                    richTextBox2.AppendText(":");
                }
                else
                {
                  richTextBox2.SelectionColor = Color.Black;
                  richTextBox2.AppendText(Convert.ToString(msg[i]));
                }
              else
              {
                richTextBox2.SelectionColor = Color.Black;
                richTextBox2.AppendText(Convert.ToString(msg[i]));
              }
    
            }
    
            richTextBox2.ReadOnly = true;
            richTextBox2.AppendText("\r\n");
    
            richTextBox2.ScrollToCaret();
    
          }
          catch (System.Exception ex)
          {
            rtberror.AppendText("EX insert_emoticons setclipboard " + ex.ToString());
          }
    
          try
          {
    
            if (nr == 1)
              Clipboard.SetAudio(clip as Stream);
            else if (nr == 2)
              Clipboard.SetFileDropList(clip as System.Collections.Specialized.StringCollection);
            else if (nr == 3)
              Clipboard.SetImage(clip as Image);
            else if (nr == 4)
              Clipboard.SetText(clip as string);
          }
          catch (System.Exception ex)
          {
            rtberror.AppendText("EX insert_emoticons " + ex.ToString());
          }
        }
    

        public void insertimage(string name)
        {
          Bitmap image1 = (Bitmap)System.Drawing.Image.FromFile(@Directory.GetCurrentDirectory() + "\\images\\emoticons\\" + name, true);
          Clipboard.SetImage(image1);
          richTextBox2.Paste();
          Clipboard.Clear();
        }
    


     

    Monday, August 15, 2011 3:04 PM
  • Hi FAndrei

    Welcome to MSDN Forum.

    "Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt

    This issue shouldn't happen in managed code. You can try setting Visual Studio Debugger to bypass this exception:

    Tools menu ->Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load"

     

    Also you can check this case about some instruction, which discussed the similar issue to yours.

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/6adca20b-649f-41a4-8fa1-09534882d76c

    I have debugged similar problems in the past and it can be very frustrating. The problem is typically caused by some component (typically unmanaged, but can also be a bad P/Invoke signature) that corrupts the program's memory. You often see differences between debug and release builds because debug builds contain extra metadata to assist in debugging. In debug mode, the corruption will kill some debug metadata, which will only cause you to see spurious debugging information, but not cause the program to crash. In release, the debug data is not present and the error overwrites critical data such as return addresses, which will cause the program to crash. You will also see small changes (like changing compiler optimizations, or re-ordering instructions) cause code to start working. What you've done is mask the problem. The memory corruption is still occuring, it's just not occuring to a critical piece of memory such as a return address. You will likely see it re-appear later as you continue modifying the code.

    This is honestly a brutal class of problems to diagnose because they're only present when you don't have debug information. Some suggestions:

    1.   Try turning on all optimizations, run the program under the debugger, and see if the error occurs. (Typically all optimizations are turned off in debug mode so that debugging is easier.) This will at least give you a way to reproduce the error when you have more debug information. This honestly won't help you a whole lot because by the time you crash, the method call that corrupted the memory is long gone.

    2.   Look at all unmanaged code that you're calling: COM objects, C/C++ DLLs, Win32 calls, etc. Check the P/Invoke signatures and COM interop thunks for all unmanaged code to verify that they're correct. Don't trust P/Invoke signatures that you find on the 'net. They're not always correct. Verify for yourself that your data types and parameter orderings are correct.

    3.   Try removing the unmanaged code (stub out the calls) and see if the problem goes away. If it does, investigate the component to verify that it is free of memory leaks. (Note that you might only be masking the problem as you re-arrange code.)

    4.   Try running your code under a unmanaged memory checker like Compuware BoundsChecker, which will look for memory leaks and access violations. This will likely give you some hints as to which unmanaged component is misbehaving.

     


    Martin Xie [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, August 19, 2011 6:06 AM
    Moderator
  • Hi all,

    I'm using visual studio 2010, and I'm getting the error when the user modifies a cell into a datagridview, as soon as the user leave the cell, the exception is thrown. Any advice?

    Thanks in advance.

    My project is compiled to .Net Framework 4.0 client profile

    PD: please excuse my english.

    Tuesday, November 20, 2012 2:49 PM
  • Hi Sir_R

    For your problem just Handle the DataError Event of DataGridView like below.

    Private Sub DataGridView1_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles _DG_DATA.DataError
    Try

    Catch ex As Exception

    End Try
    End Sub

    Thursday, December 13, 2012 7:04 AM
  • Hello all,

    I would like to continue this thread with an issue that i have recently . 

    The application that i have has the target framework to 4.0 and is written in C# using Visual Studio 2010 and uses Windows Forms for the UI. My application loads DLL's written in C++ or LabView and executes some methods from those DLL's . 

    This is the error that is reported (sometimes) :

    When :

    1) I make the following call : System.Windows.Forms.Clipboard.SetText("text");

             OR 

    2) Using "Delete" key from the keyboard i edit the content of a text box .

    For both 1) and 2)  exists a try { ... } catch(Exception) that is not able to catch this error.

    My problem is that every time this kind of error appears, the application displays this message , that is caught in a method of the program and then closes, after OK is pressed. I don't know where to catch this error and make the application continue somehow ; At the moment this error is caught in the in the "main" method of the UI:

    [STAThread]
    private static void Main()
    try
     { 
        Application.Run(GetInstance());
     }catch (Exception e)
     {
       MessageBox.Show(e.Message + " ---> "+ e.StackTrace,"Error in system");
    
     }
    Any help would be appreciated.


    Tuesday, October 8, 2013 10:17 AM