Someone Else
Someone Else

Reputation: 2803

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.

Upvotes: 214

Views: 577834

Answers (30)

Travis J
Travis J

Reputation: 82277

This is an annoying but vague exception message. While it is clear that there was a problem, it can be difficult to trace. Often, a line of code will be highlighted where the problem occurred, but this is not consistent nor verifiable with regards to what is happening.

The vague nature of this exception comes from the most likely scenario: that your computer ran out of memory but the code kept executing. This can happen when pointers are being used for memory, during marshalling, or when using unsafe code.

While there may be a way to kick the can down the road by making optimizations or fixing memory leaks, another approach is to simply add more memory. In most modern environments, this can be done by expanding the virtual memory if using a SSD.

In Windows 11, you can do this by running sysdm.cpl, then going to Advanced -> Performance Settings -> Advanced, and increasing the maximum virtual memory to something that fits your needs. This is best used temporarily, or if you have a significant amount of extra SSD space available.

Upvotes: 0

Andrew
Andrew

Reputation: 13221

Apple Mx Macs (Apple Silicon) This error can also be caused by dotnet restore being called while building a Dockerfile, when the Mac's environment has the following configuration:

DOCKER_DEFAULT_PLATFORM=linux/amd64

To fix it, in the same terminal/console we're running the docker build . command, run:

unset DOCKER_DEFAULT_PLATFORM

then the docker build . command should succeed.

Upvotes: 1

RBT
RBT

Reputation: 25897

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

Upvotes: 48

Praveen Patel G
Praveen Patel G

Reputation: 362

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.

Upvotes: 0

curiousBoy
curiousBoy

Reputation: 6834

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.

Upvotes: 10

dezox
dezox

Reputation: 179

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.

Upvotes: 0

Sher Singh
Sher Singh

Reputation: 545

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

Upvotes: 2

ibrahim ünal
ibrahim ünal

Reputation: 109

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

Upvotes: 0

nvbnvb
nvbnvb

Reputation: 84

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.

Upvotes: 0

Craig T
Craig T

Reputation: 1061

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.

Upvotes: 0

mohghaderi
mohghaderi

Reputation: 2650

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;
    }

Upvotes: 1

melicent
melicent

Reputation: 1251

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.

Upvotes: 0

101
101

Reputation: 8999

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.

Upvotes: 0

Charlie
Charlie

Reputation: 9108

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);

Upvotes: 8

Vivek Sharma
Vivek Sharma

Reputation: 2062

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.

Upvotes: 2

Netricity
Netricity

Reputation: 2738

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.

Upvotes: 0

user8128167
user8128167

Reputation: 7676

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/

Upvotes: 1

T.Todua
T.Todua

Reputation: 56371

In some cases, this might happen when:

obj = new obj();
...
obj.Dispose();  // <-----------------    Incorrect disposal causes it
obj.abc...

Upvotes: -1

Eternal21
Eternal21

Reputation: 4664

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)

Upvotes: 1

Muhammad Yousaf Sulahria
Muhammad Yousaf Sulahria

Reputation: 1728

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.

Upvotes: 32

Tony Raymond
Tony Raymond

Reputation: 187

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.

Upvotes: 2

ako
ako

Reputation: 2126

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 .

Upvotes: 1

Sonic Soul
Sonic Soul

Reputation: 24919

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);
    }

Upvotes: 2

gbro3n
gbro3n

Reputation: 6967

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

Upvotes: 6

Barrie
Barrie

Reputation: 1474

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.

Upvotes: 1

BornToCode
BornToCode

Reputation: 10213

Try to run this command

netsh winsock reset

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

Upvotes: 15

almulo
almulo

Reputation: 4978

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

Upvotes: 4

Sergey
Sergey

Reputation: 1009

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.

Upvotes: 76

kmxr
kmxr

Reputation: 479

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)

Upvotes: 5

deepakg_rao
deepakg_rao

Reputation: 51

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.

Upvotes: 5

Related Questions