199

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Someone Else
  • 2,625
  • 3
  • 20
  • 15
  • please post the full call stack... – Mitch Wheat Nov 02 '10 at 02:56
  • possible duplicate of [Troubleshooting .NET "Fatal Execution Engine Error"](http://stackoverflow.com/questions/2823440/troubleshooting-net-fatal-execution-engine-error) – Hans Passant Nov 02 '10 at 03:05
  • About half the time I cannot get the call stack. If it throws the fatal execution error there is no debugging information at all. The times that it actually does stop somewhere in the code, nothing seems abnormal. I've even gone through all the active threads and havent seen anything that could cause a conflict. I'm assuming the memory corruption happened some time before it threw the error. – Someone Else Nov 02 '10 at 03:07
  • Check for crappy old COM and ActiveX components being used. I also know SQLCE craps outs like this in a multithreaded environment. – leppie Nov 02 '10 at 03:48
  • There are no COM or ActiveX components. – Someone Else Nov 03 '10 at 22:41
  • I have this problem, too. I'm using paradox 5.x, .net 3.5 and sage data object(com component), It happens randomly I can't find a pattern of it. I think it's just some dodge code in the com component. – Larry Oct 11 '12 at 15:24
  • you can also get it by accessing a resource that is locked by something, like a Excel file being open already. Posted this as an answer since that was my issue. – Sonic Soul Oct 13 '15 at 20:29
  • Surprisingly it is happening for ONLY one of the projects in my solution. I've got a dozen of projects in my solution but all others run without any issue. The one in which I'm facing this issue is a C# console application. To add to info, I had taken a huge bulk of pending windows 7 update in the morning yesterday but if that would have been the root cause then it should have affected the startup pattern of all the projects in the solution. I'm using Visual Studio 2010. The issue happens only during debugging the project from VS. Its output exe from debug folder works perfect. – RBT Jun 17 '16 at 00:59

33 Answers33

70

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.

Sergey
  • 939
  • 1
  • 6
  • 13
  • 1
    how did you change it back with x86. I'm just facinf the same problem with this instruction `CSingleLock lock(&m_csMember, TRUE);`. [For more details, here is my post](http://stackoverflow.com/questions/22285044/error-additional-information-attempted-to-read-or-write-protected-memory-this) – ABCmo Mar 12 '14 at 14:54
  • In VS 2012/2013, go to Project Properties->Build and change "Platform Target" to whatever you need. Though I think there is another place where you can change this, but I cannot seem to find it, I think either ways *should* achieve the same outcome. – Sergey Mar 13 '14 at 14:01
  • I'm actually using VS 2013, and it's configured as x86 :/ – ABCmo Mar 13 '14 at 20:28
  • 1
    Your problem can be caused by many things, I was really surprised that I fixed my problem by changing the build platform. You could say a lucky escape. – Sergey Mar 17 '14 at 09:26
  • This solution in combination with [this answer](http://stackoverflow.com/a/27260580/2517147) solved it for me. – Zach Olivare Nov 29 '16 at 17:14
38

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

Update 2 (22-Apr-2023): In VS 2022, it is available under Debugger engines section in Debug tab (Refer screenshot):

enter image description here

RBT
  • 24,161
  • 21
  • 159
  • 240
30

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.

Muhammad Yousaf Sulahria
  • 1,708
  • 1
  • 14
  • 16
25

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.

Someone Else
  • 2,625
  • 3
  • 20
  • 15
14

Try to run this command

netsh winsock reset

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

Community
  • 1
  • 1
BornToCode
  • 9,495
  • 9
  • 66
  • 83
10

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.

RBT
  • 24,161
  • 21
  • 159
  • 240
curiousBoy
  • 6,334
  • 5
  • 48
  • 56
  • 3
    I'm sorry that it hasn't work for you. This error is raised for a lot of reasons, I thought, the solution that I have posted , may solve the problem for someone else if the reason is JIT optimization. – curiousBoy Jun 10 '13 at 20:36
8

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);
Charlie
  • 8,530
  • 2
  • 55
  • 53
6

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

gbro3n
  • 6,729
  • 9
  • 59
  • 100
5

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.

deepakg_rao
  • 51
  • 1
  • 1
5

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)

kmxr
  • 479
  • 4
  • 4
  • i'm facing the same issue - autocad .net dll - can you elaborate on what the problem and fix was? – BenKoshy Dec 08 '17 at 05:39
  • Ran into this today as well using CAD 2023. I am creating a .net DLL and made a reference to Autodesk.AutoCAD.Interop.Common. Removing this reference (in the code itself, not a project reference) fixed it. Oddly enough, that particular line of code WORKED for several iterations of the loop it was in. Then it decided to not work. – Thomas Bailey Mar 28 '23 at 21:25
5

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?

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 2
    Running XP 64 SP2. This has happened on multiple servers though. I've gone through everything so many times and i dont see anything thats not thread safe. Also wouldnt i be getting a collection modified error rather than a access viloation? – Someone Else Nov 02 '10 at 03:10
4

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...

almulo
  • 4,918
  • 1
  • 20
  • 29
4

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

alhazen
  • 1,907
  • 3
  • 22
  • 43
  • 3
    I'm not sure _that's_ a good idea. It may well delay the crash but at the cost of doing more damage. I think the best idea, if you're going to crash, is to crash early :-) – paxdiablo Nov 02 '10 at 03:03
  • 2
    Turning off DEP is unwise but a useful diagnostic exercise. – vcsjones Nov 02 '10 at 03:18
4

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.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
2

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);
    }
Sonic Soul
  • 23,855
  • 37
  • 130
  • 196
2

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.

Tony Raymond
  • 187
  • 10
2

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.

Vivek Sharma
  • 1,912
  • 1
  • 13
  • 15
2

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

Sher Singh
  • 497
  • 5
  • 8
1

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.

Community
  • 1
  • 1
Barrie
  • 1,444
  • 19
  • 26
1

i had this problem too . i was running different solutions at the same time using visual studio , when closing other solutions and running just the target solution , it worked fine without that error .

ako
  • 2,000
  • 2
  • 28
  • 34
1

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 3
    You can get a corrupted pointer from bad memory as well. If this is not happening on a server with ECC memory, try a long-running memory test utility to eliminate the hardware as a cause. – cdonner Nov 02 '10 at 02:55
  • 13
    I know its not a hardware issue cause it happens on multiple servers. Thanks for indicating theres something bad in the code captain obvious. I'm not blaming visual studio. As stated the application runs fine for a random period of time. Its not easy to reproduce and i've been trying to identify the issue for weeks now. – Someone Else Nov 02 '10 at 02:59
  • 6
    @Someone Else: I hardly think name calling is going to get you much help. – Mitch Wheat Nov 02 '10 at 03:02
  • 2
    @Someone Else, I've helped as much as I can given the limited information you've provided. Even the best doctor in the world can't do much with a patient who simply states "I hurt" :-) If you'd like to provide more specific information, then maybe we can help more. – paxdiablo Nov 02 '10 at 03:06
  • I've provided everything I can think of and will answer any questions. I'm just looking for any ideas because at this point i'm out. – Someone Else Nov 02 '10 at 03:12
  • @Someone Else, I've given my thoughts - it may well come down to laborious examination of the possibilities. – paxdiablo Nov 02 '10 at 03:17
  • Given the limited information (I'm sorry, i wish i knew more of what was going on and maybe i wouldnt need to be posting here) is there anything specifically you would look for first? – Someone Else Nov 02 '10 at 03:21
  • 1
    (1) What is corrupt (which specific pointer)? (2) Are there other corrupt things near there? (3) Is the a pattern to the corruption (e.g., has a set of integer been overwritten by a known string from a data file, or user input)? (4) Are there any buffers near the corruption? That's hopefully a good start but, short of seeing code, there's not much else other than looking into the valgrind-type options (which may well be better than looking at the code anyway). – paxdiablo Nov 02 '10 at 03:28
  • 5
    Bad Answer, but approach, shameless speculation, unjustified assumptions, no solution provided...Why is this answer still up? And what 3 people could possible have upvoted this answer? – ThunderGr Apr 03 '14 at 07:01
  • @Thunder, I provide several avenues for investigation and, given the question, there wasn't enough info for more. However, if you think it unhelpful, vote it down, that's what the votes are for. Those other 3 people seemed to consider it useful. Or, better yet, you could consider refraining from carping about other's answers and post your own. If it's better, it will soon rise above mine. This is a meritocracy after all. – paxdiablo Apr 03 '14 at 08:09
  • 2
    I am searching for a solution to the problem posted by the OP, not to give a solution. Every other answer has a working solution for the person that had experienced the problem. Unfortunately, it is not "bad code" as you state and it may not be the fault of visual studio per se, it is a problem of .Net that fails to provide something meaningful when an access violation happens. It is not our responsibility to know how .Net interacts with the various .dlls present in a machine that are unrelated to our code. So,your assumptions and speculations are wrong and unhelpful. – ThunderGr Apr 03 '14 at 11:53
  • @Thunder, I still maintain that, given the info in the question, there was no possibility of a definite answer. The accepted answer was from the OP themselves, no doubt with the benefit of access to the system. But I reiterate, if you think it's unhelpful,then you should vote it down, that's the way the voting system works. – paxdiablo Apr 03 '14 at 12:47
  • We could discuss it for months and probably end up agreeing to disagree. But the way to influence where answers show up is to use your votes. I won't be annoyed if you do, I have very thick skin :-) – paxdiablo Apr 03 '14 at 12:55
  • "if this were a problem with VS, we would probably already have found it.". People have hundreds of issues with VS, and most still waiting to be fixed. – Steve Smith Apr 30 '21 at 14:07
  • @Steve, my point was not that there are *no* issues with VS, it's that there are relatively few *unknown* issues, simply due to the large number of people using it and therefore finding those issues. Those hundreds of issues you mention, while yet unfixed, are still known. I still stand behind that suggestion. If you have a piece of code used by ten million people and another used by one person, simple statistics dictates that the former will be more likely to approach an error-free state over time. – paxdiablo Apr 30 '21 at 23:47
1

Got this error randomly in VS1017, when trying to build a project that was building perfectly fine the day before. Restarting the PC fixed the issue worked (I also ran the following command beforehand, not sure if it's required: netsh winsock reset)

Eternal21
  • 4,190
  • 2
  • 48
  • 63
  • 1
    That is exactly my situation with VS 2017 - System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. I simply restarted PC to solve this problem without doing anything else. – Hong May 28 '19 at 14:52
1

In my case I had to reference a C/C++ library using P/Invoke, but I had to ensure that the memory was allocated for the output array first using fixed:

[DllImport("my_c_func_lib.dll", CharSet = CharSet.Ansi)]
public static extern unsafe int my_c_func(double input1, double input2, double pinput3, double *outData);

    public unsafe double[] GetMyUnmanagedCodeValue(double input1, double input2, double input3)
    {
        double[] outData = new double[24];

        fixed (double* returnValue = outData)
        {
            my_c_func(input1, input2, pinput3, returnValue);
        }

        return outData;
    }

For details please see: https://www.c-sharpcorner.com/article/pointers-in-C-Sharp/

user8128167
  • 6,929
  • 6
  • 66
  • 79
0

This happened to me when I was debugging my C# WinForms application in Visual Studio. My application makes calls to Win32 stuff via DllImport, e.g.

[DllImport("Secur32.dll", SetLastError = false)]
private static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);

Running Visual Studio "as Administrator" solved the problem for me.

Netricity
  • 2,550
  • 1
  • 22
  • 28
0

In my case the FTDI utility FT Prog was throwing the error as it scanned for USB devices. Unplugging my Bluetooth headphones from the PC fixed the issue.

101
  • 8,514
  • 6
  • 43
  • 69
0

I got this error message on lambda expression that was using Linq to filter a collection of objects. When I inspected the collection I noticed that its members weren't populated - in the Locals window, expanding them just showed "...". Ultimately the problem was in the repository method that initially populated the collection - Dapper was trying to automatically map a property of a nested object. I fixed the Dapper query to handle the multi-mapping and that fixed the memory error.

melicent
  • 1,221
  • 15
  • 22
0

This may not be the best answer for the above question, but the problem of mine was invalid dispose syntax and usage of lock(this) for a buffer object. It turned out the object was getting disposed from another thread because of "using" syntax. And the processing lock() was on a loose type.

// wrong lock syntax
lock(this) {
    // modify buffer object
}

I changed the locks to

private static readonly object _lockObject = new object();

lock(_lockObject) {
    // modify buffer object
}

And used suggested C# disposing syntax and the problem gone.

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            // Free any managed objects here
            buffer?.Free();
        }

        disposed = true;
    }
mohghaderi
  • 2,520
  • 1
  • 19
  • 12
0

I've experienced the same issue when running a .Net Framework Web API application locally under IIS.

The issue was that I had previously updated the IIS App Pool's Managed Pipeline Mode to 'Classic'. Setting it back to 'Integrated' fixed the issue for me.

Craig T
  • 1,031
  • 1
  • 7
  • 13
0

For Xamarin Forms one can wrap the code in

Device.BeginInvokeOnMainThread(() => 
{
 //your code
});

Happened for me in UWP when updating UI from the wrong thread.

nvbnvb
  • 76
  • 5
0

I had the same issue just because trying to overwrite my model while updating on Angular Service.

var nu: ExtendedUserSettingModel = this.addUserForm1.value;
// nu.createdOn = this.date; //this was what caused the issue

make sure you do not overwrite any written data

0

If anyone is here after all these years, and still has not found any solution, here is another one:

Im having a .net web api, and got this error also.

The solution was to take a look at the api project, and under the Properties, changed "Managed Pipeline Mode" to Integrated, instead of classic.

dezox
  • 146
  • 9
0

As many folks saying there are many reasons causing this error. But the first and foremost reason is a variable or object which you are using to store and retrieve data very frequently is consuming more memory. Just find it out and eliminate that if that is not required or use separate thread for such executions or any other ideas if you get.

Praveen Patel G
  • 342
  • 4
  • 13
-1

In some cases, this might happen when:

obj = new obj();
...
obj.Dispose();  // <-----------------    Incorrect disposal causes it
obj.abc...
T.Todua
  • 53,146
  • 19
  • 236
  • 237