Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I'm hoping someone can enlighten me as to what could possibly be causing this error:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I cannot really post code because this error seems to get thrown in any random area of the application. The application will run anywhere from 12-48 hours before throwing the error. Sometimes it will stop in a seemingly random spot and throw the above error, other times the entire application stops and I get a screen with an error that says something along the lines of "There was a fatal error in... This may be a bug in the CLR or..." something about PInvoke or other non relevant info. When this happens all threads show terminated and there is no debugging information available.

In a nutshell this is what the application does:

Its a multi-threaded server application written in entirely in C#. Clients connect to the server via socket. The server runs a virtual "environment" for the clients where they can interact with each other and the environment. It consumes quite a bit of memory but I do not see it leaking. It typically consumes about 1.5GB. I dont think its leaking because the memory usage stays relatively constant the entire time the application is running. Its constantly running code to maintain the environment even if the clients are not doing anything. It uses no 3rd party software or other APIs. The only outside resources this application uses is socket connections and SQL database connections. Its running on a 64bit server. I have tried debugging this in VS2008 & VS2010 using .net 2.0, 3.5, and 4.0 and on multiple servers and the problem still eventually occurs.

I've tried turning off compiler optimizations and several microsoft hot-fixes. Nothing seems to make this issue go away. It would be appreciated if anyone knows any possible causes, or some kind of way to identify whats causing the problem.

like image 604
Someone Else Avatar asked Nov 02 '10 02:11

Someone Else


People also ask

What is System AccessViolationException?

An AccessViolationException exception is always thrown by an attempt to access protected memory -- that is, to access memory that is not allocated or that is not owned by a process. Automatic memory management is one of the services that the common language runtime provides.


20 Answers

I have just faced this issue in VS 2013 .NET 4.5 with a MapInfo DLL. Turns out, the problem was that I changed the Platform for Build from x86 to Any CPU and that was enough to trigger this error. Changing it back to x86 did the trick. Might help someone.

like image 58
Sergey Avatar answered Oct 01 '22 03:10

Sergey


I faced this issue with Visual Studio (VS) 2010. More interestingly, I had several types of projects in my solution namely a console application project, a WPF application project, a Windows Forms application project, etc. But it was failing only when, I was setting the Console Application type of project as start-up project of the solution. All the projects were completely empty. They had no user code or any 3rd party assemblies added as reference. All projects are referencing only the default assemblies of .NET base class library (BCL) which come with the project template itself.

How to solve the issue?

Go to project properties of the console application project (Alternately you can select the project file in solution explorer and press Alt + Enter key combination) > Go to Debug tab > Check the Enable unmanaged code debugging check box under Enable Debuggers section (refer screenshot) > Click Floppy button in the toolbar to save project properties.

enter image description here

Root cause of the issue is not known to me. Only thing I observed was that there were lot of windows updates which had got installed on my machine the previous night. All the updates constituted mostly of office updates and OS updates (More than a dozen KB articles).

Update: VS 2017 onward the setting name has changed to Enable native code debugging. It is available under Debugger engines section (refer screenshot):

enter image description here

like image 35
RBT Avatar answered Oct 02 '22 03:10

RBT


The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved.

like image 34
Muhammad Yousaf Sulahria Avatar answered Oct 01 '22 03:10

Muhammad Yousaf Sulahria


Finally tracked this down with the help of WinDBG and SOS. Access violation was being thrown by some unknown DLL. Turns out a piece of software called "Nvidia Network Manager" was causing the problems. I'd read countless times how this issue can be caused by firewalls or antivirus, neither of which I am using so I dismissed this idea. Also, I was under the assumption that it was not environmental because it occurs on more than 1 server using different hardware. Turns out all the machines I tested this on were running "NVidia Network Manager". I believe it installs with the rest of the motherboard drivers.

Hopefully this helps someone as this issue was plaguing my application for a very long time.

like image 23
Someone Else Avatar answered Oct 01 '22 03:10

Someone Else


Try to run this command

netsh winsock reset

Source: https://stackoverflow.com/a/20492181/1057791

like image 22
BornToCode Avatar answered Sep 28 '22 03:09

BornToCode


This error should not happen in the managed code. This might solve the issue:

Go to Visual Studio Debugger to bypass this exception:

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

Hope it will help.

like image 22
curiousBoy Avatar answered Sep 30 '22 03:09

curiousBoy


I got this error when using pinvoke on a method that takes a reference to a StringBuilder. I had used the default constructor which apparently only allocates 16 bytes. Windows tried to put more than 16 bytes in the buffer and caused a buffer overrun.

Instead of

StringBuilder windowText = new StringBuilder(); // Probable overflow of default capacity (16)

Use a larger capacity:

StringBuilder windowText = new StringBuilder(3000);
like image 37
Charlie Avatar answered Sep 29 '22 03:09

Charlie


I've ran into, and found a resolution to this exception today. It was occurring when I was trying to debug a unit test (NUnit) that called a virtual method on an abstract class.

The issue appears to be with the .NET 4.5.1 install.

I have downloaded .NET 4.5.2 and installed (my projects still reference .NET 4.5.1) and the issue is resolved.

Source of solution:

https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception

like image 21
gb2d Avatar answered Oct 02 '22 03:10

gb2d


It could be hardware. It could be something complicated...but I'd take a stab at suggesting that somewhere your threading code is not protecting some collection (such as a dictionary) with an appropriate lock.

What OS and service pack are you running?

like image 20
Mitch Wheat Avatar answered Sep 29 '22 03:09

Mitch Wheat


I had this problem recently when I changed the development server for a project. I was getting this error on the line of code where I declared a new OracleConnection variable.

After trying many things, including installing hotfixes, I tried changing the references Oracle.DataAccess and System.Data.OracleClient in the project and it worked!

When a project is moved to a new machine, I suggest you renew all the references added in that project.

like image 45
deepakg_rao Avatar answered Sep 29 '22 03:09

deepakg_rao


Did you try turning off DEP (Data Execution Prevention) for your application ?

like image 29
alhazen Avatar answered Sep 28 '22 03:09

alhazen


Verifiable code should not be able to corrupt memory, so there's something unsafe going on. Are you using any unsafe code anywhere, such as in buffer processing? Also, the stuff about PInvoke may not be irrelevant, as PInvoke involves a transition to unmanaged code and associated marshaling.

My best recommendation is to attach to a crashed instance and use WinDBG and SOS to dig deeper into what's happening at the time of the crash. This is not for the faint of heart, but at this point you may need to break out more powerful tools to determine what, exactly, is going wrong.

like image 32
Dan Bryant Avatar answered Oct 02 '22 03:10

Dan Bryant


I faced the same issue. My code was a .NET dll (AutoCAD extension) running inside AutoCAD 2012. I am also using Oracle.DataAccess and my code was throwing the same exception during ExecuteNonQuery(). I luckily solved this problem by changing the .net version of the ODP I was using (that is, 2.x of Oracle.DataAccess)

like image 25
kmxr Avatar answered Sep 30 '22 03:09

kmxr


Ok, this could be pretty useless and simply anecdotal, but...

This exception was thrown consistently by some Twain32 libraries we were using in my project, but would only happen in my machine.

I tried lots of suggested solutions all over the internet, to no avail... Until I unplugged my cellphone (it was connected through the USB).

And it worked.

Turns out the Twain32 libraries were trying to list my phone as a Twain compatible device, and something it did in that process caused that exception.

Go figure...

like image 38
almulo Avatar answered Sep 28 '22 03:09

almulo


in my case the file was open and therefore locked.

I was getting it when trying to load an Excel file using LinqToExcel that was also opened in Excel.

this is all I deeded

    var maps = from f in book.Worksheet<NavMapping>()
                select f;
    try {
        foreach (var m in maps)
            if (!string.IsNullOrEmpty(m.SSS_ID) && _mappings.ContainsKey(m.SSS_ID))
                _mappings.Add(m.SSS_ID, m.CDS_ID);
    } catch (AccessViolationException ex) {
        _logger.Error("mapping file error. most likely this file is locked or open. " + ex);
    }
like image 20
Sonic Soul Avatar answered Oct 01 '22 03:10

Sonic Soul


I got the same error in a project I was working with in VB.NET. Checking the "Enable application framework" on the properties page solved it for me.

like image 40
Tony Raymond Avatar answered Sep 29 '22 03:09

Tony Raymond


I had the same error message:

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

In my case, the error went away after clean and re-build the solution.

like image 34
Vivek Sharma Avatar answered Sep 28 '22 03:09

Vivek Sharma


Make sure you are not creating multiple time converter objects. you can use to singleton class to create a converter object to resolve the below error with Haukcode.WkHtmlToPdfDotNet library

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

enter image description here

like image 2
Sher Singh Avatar answered Oct 01 '22 03:10

Sher Singh


This issue is almost invariably a simple one. The code is bad. It's rarely the tools, just from a statistical analysis. Untold millions of people are using Visual Studio every day and maybe a few are using your code - which bit of code is getting the better testing? I guarantee that, if this were a problem with VS, we would probably already have found it.

What the statement means is that, when you try to access memory that isn't yours, it's usually because you're doing it with a corrupted pointer, that came from somewhere else. That's why it's stating the indication.

With memory corruption, the catching of the error is rarely near the root cause of the error. And the effects are exactly what you describe, seemingly random. You'll just have to look at the usual culprits, things like:

  • uninitialised pointers or other values.
  • writing more to a buffer than its size.
  • resources shared by threads that aren't protected by mutexes.

Working backwards from a problem like this to find the root cause is incredibly difficult given that so much could have happened between the creation of the problem and the detection of the problem.

I mostly find it's easier to have a look at what is corrupt (say, a specific pointer) and then do manual static analysis of the code to see what could have corrupted it, checking for the usual culprits as shown above. However, even this won't catch long chains of problems.

I'm not familiar enough with VS to know but you may also want to look into the possibility of using a memory tracking tool (like valgrind for Linux) to see if it can spot any obvious issues.

like image 1
paxdiablo Avatar answered Oct 01 '22 03:10

paxdiablo


My answer very much depends on your scenario but we had an issue trying to upgrade a .NET application for a client which was > 10 years old so they could make it work on Windows 8.1. @alhazen's answer was kind of in the correct ballpark for me. The application was relying on a third-party DLL the client didn't want to pay to update (Pegasus/Accusoft ImagXpress). We re-targeted the application for .NET 4.5 but each time the following line executed we received the AccessViolationException was unhandled message:

UnlockPICImagXpress.PS_Unlock (1908228217,373714400,1341834561,28447);

To fix it, we had to add the following post-build event to the project:

call "$(DevEnvDir)..\tools\vsvars32.bat"
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\amd64\editbin.exe" /NXCOMPAT:NO "$(TargetPath)"

This explicitly specifies the executable as incompatible with Data Execution Prevention. For more details see here.

like image 1
Barrie Avatar answered Oct 01 '22 03:10

Barrie