Why in C# Console applications from template is crashes? [duplicate] - c#

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.

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.

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

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.

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.

Try to run this command
netsh winsock reset
Source: https://stackoverflow.com/a/20492181/1057791

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.

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

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

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?

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.

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

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.

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)

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

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

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.

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.

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

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.

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.

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 .

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)

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/

In some cases, this might happen when:
obj = new obj();
...
obj.Dispose(); // <----------------- Incorrect disposal causes it
obj.abc...

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.

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.

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.

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

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.

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.

Related

C# : catch all errors/exceptions of a mixed managed/unmanaged process

I have a big and complex process that runs on a production environment that's basically a WPF user interface developed in C#. It also hosts threads and DLL's written in C++ unmanaged and managed code.
Typically, if an exception raises, it's caught and the related stack dump is written in a log file for post-mortem debugging purposes. Unfortunately, from time to time, the application crashes without writing any information in the log so we have no clue about who's causing the crash.
Does anybody know how to detect and eventually trace all the causes that make the application crash and are not detected with a simple try-catch block?
To give an example I saw that StackOverflow Exception is not caught and also errors like 0xc0000374 coming from unmanaged code are not detected. This is not a matter of debugging it. I know I can attach a debugger to the system and try to reproduce the problem. But as I told this is a production system and I have to analyze issues coming from the field after the problem occurred.
Unlike C# exceptions, C++ exceptions do not catch hardware exceptions such as access violations or stack overflows since C++ apps run unmanaged and directly on the cpu.
For post-crash analysis I would suggest using something like breakpad. breakpad will create a dump file which will give you very useful information such as a call-stack, running threads and stack/heap memory depending on your configuration.
This way you would not need to witness the crash happening or even try to reproduce it which I know from experience can be very difficult. All you would need is a way to retrieve these crash dumps from your users devices.
You can log exception by subscribing to AppDomain.UnhandledException event. Its args.ExceptionObject argument is of type object and is designed not to be limited by C# exceptions, so you can call ToString method to log it somewhere.
Also check MSDN docs for its limitations. For instance:
Starting with the .NET Framework 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.
Solved ! I followed Mohamad Elghawi suggestion and I integrated breakpad. After I struggled a lot in order to make it compiling, linking and working under Visual Studio 2008, I was able to catch critical system exceptions and generate a crash dump. I'm also able to generate a dump on demand, this is useful when the application stuck for some reason and I'm able to identify this issue with an external thread that monitors all the others.
Pay attention ! The visual studio solution isn't included in the git repo and the gyp tool, in contradiction as wrongly mentioned in some threads, it's also not there. You have to download the gyp tool separately and work a bit on the .gyp files inside the breadpad three in order to generate a proper solution. Furthermore some include files and definitions are missing if you want to compile it in Visual Studio 2008 so you have also to manage this.
Thanks guys !

Debug Assertion Failed: C++ exception in a C# application?

I have been managing and updating a particular application. It is old and I am not the original developer. It's suffered through several debugging sessions over the years among other small patches.
It has been running stable for the last couple of months, but then an exception occurred that seems odd to me. Since this only happens on the server ( it is a server application. ) in release mode.
The application is written in C#, is managed in Visual Studio 2012 Professional and is released to be explicitly 32-bit .NET 3.5 since the server is unfortunately running Windows 2003. (I have tried to convince them to update so I can update the application to .NET 4.5. But alas.)
So I am getting a C++ Debug message. See the screenshot below. It occurs in a file named vsprintf.c I am guessing on line 91. The only message that gives me any hint is format != NULL.
This confuses me however. What can possibly cause this? What steps can I best take to debug in a situation like this? What is "vsprintf.c"?
Edit: I managed to find something in eventviewer. I will continue to research this in the meanwhile.
Sincerely,
me.
This is an assertion failure, ie an assumtion that a function you are calling makes is not met, in this case that a pointer is not null. From the looks of it, its a format string. Are you using format strings directly? If so, look there. If not, this is probably a memory leak problem, followed by an out-of-memory malfunction.
vsprintf calls can be caused by sprintf and other derivates, you should maybe check all these calls. (This can also be methods of string classes, as I saw in the VCL).
If the bug isn't caused by one of the libraries you use, then there should be a NULL (or 0) in the format string parameter, which is mostly the last before the ... in the prototype.
If you are familiar with regular expressions, this may help a lot when looking for patterns.

How can I debug an internal error in the .NET Runtime?

I am trying to debug some work that processes large files. The code itself works, but there are sporadic errors reported from the .NET Runtime itself. For context, the processing here is a 1.5GB file (loaded into memory once only) being processed and released in a loop, deliberately to try to reproduce this otherwise unpredictable error.
My test fragment is basically:
try {
byte[] data =File.ReadAllBytes(path);
for(int i = 0 ; i < 500 ; i++)
{
ProcessTheData(data); // deserialize and validate
// force collection, for tidiness
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
}
} catch(Exception ex) {
Console.WriteLine(ex.Message);
// some more logging; StackTrace, recursive InnerException, etc
}
(with some timing and other stuff thrown in)
The loop will process fine for an non-deterministic number of iterations fully successfully - no problems whatsoever; then the process will terminate abruptly. The exception handler is not hit. The test does involve a lot of memory use, but it saw-tooths very nicely during each iteration (there is not an obvious memory leak, and I have plenty of headroom - 14GB unused primary memory at the worst point in the saw-tooth). The process is 64-bit.
The windows error-log contains 3 new entries, which (via exit code 80131506) suggest an Execution Engine error - a nasty little critter. A related answer, suggests a GC error, with a "fix" to disable concurrent GC; however this "fix" does not prevent the issue.
Clarification: this low-level error does not hit the CurrentDomain.UnhandledException event.
Clarification: the GC.Collect is there only to monitor the saw-toothing memory, to check for memory leaks and to keep things predictable; removing it does not make the problem go away: it just makes it keep more memory between iterations, and makes the dmp files bigger ;p
By adding more console tracing, I have observed it faulting during each of:
during deserialization (lots of allocations, etc)
during GC (between a GC "approach" and a GC "complete", using the GC notification API)
during validation (just foreach over some of the data) - curiously just after a GC "complete" during the validation
So lots of different scenarios.
I can obtain crash-dump (dmp) files; how can I investigate this further, to see what the system is doing when it fails so spectacularly?
If you have memory dumps, I'd suggest using WinDbg to look at them, assuming that you're not doing that already.
Trying running the comment !EEStack (mixed native and managed stack trace), and see if there's anything that might jump out in the stack trace. In my test program, I found this one of the times as my stack trace where a FEEE happened (I was purposefully corrupting the heap):
0:000> !EEStack
---------------------------------------------
Thread 0
Current frame: ntdll!NtWaitForSingleObject+0xa
Child-SP RetAddr Caller, Callee
00000089879bd3d0 000007fc586610ea KERNELBASE!WaitForSingleObjectEx+0x92, calling ntdll!NtWaitForSingleObject
00000089879bd400 000007fc5869811c KERNELBASE!RaiseException+0x68, calling ntdll!RtlRaiseException
[...]
00000089879bec80 000007fc49109cf6 clr!WKS::gc_heap::gc1+0x96, calling clr!WKS::gc_heap::mark_phase
00000089879becd0 000007fc49109c21 clr!WKS::gc_heap::garbage_collect+0x222, calling clr!WKS::gc_heap::gc1
00000089879bed10 000007fc491092f1 clr!WKS::GCHeap::RestartEE+0xa2, calling clr!Thread::ResumeRuntime
00000089879bed60 000007fc4910998d clr!WKS::GCHeap::GarbageCollectGeneration+0xdd, calling clr!WKS::gc_heap::garbage_collect
00000089879bedb0 000007fc4910df9c clr!WKS::GCHeap::Alloc+0x31b, calling clr!WKS::GCHeap::GarbageCollectGeneration
00000089879bee00 000007fc48ff82e1 clr!JIT_NewArr1+0x481
Since this could be related to heap corruption from the garbage collector, I would try the !VerifyHeap command. At least you could make sure that the heap is intact (and your problem lies elsewhere) or discover that your issue might actually be with the GC or some P/Invoke routines corrupting it.
If you find that the heap is corrupt, I might try and discover how much of the heap is corrupted, which you might be able to do via !HeapStat. That might just show the entire heap corrupt from a certain point, though.
It's difficult to suggest any other methods to analyze this via WinDbg, since I have no real clue about what your code is doing or how it's structured.
I suppose if you find it to be an issue with the heap and thus meaning it could be GC weirdness, I would look at the CLR GC events in Event Tracing for Windows.
If the minidumps you're getting aren't cutting it and you're using Windows 7/2008R2 or later, you can use Global Flags (gflags.exe) to attach a debugger when the process terminates without an exception, if you're not getting a WER notification.
In the Silent Process Exit tab, enter the name of the executable, not the full path to it (ie. TestProgram.exe). Use the following settings:
Check Enable Silent Process Exit Monitoring
Check Launch Monitor Process
For the Monitor Process, use {path to debugging tools}\cdb.exe -server tcp:port=5005 -g -G -p %e.
And apply the settings.
When your test program crashes, cdb will attach and wait for you to connect to it. Start WinDbg, type Ctrl+R, and use the connection string: tcp:port=5005,server=localhost.
You might be able to skip using remote debugging and instead use {path to debugging tools}\windbg.exe %e. However, the reason I suggested remote instead, was because WerFault.exe, which I believe is what reads the registry and launches the monitor process, will start the debugger in Session 0.
You can make session 0 interactive and connect to the window station, but I can't remember how that's done. It's also inconvenient, because you'd have to switch back and forth between sessions if you need to access any of your existing windows you've had open.
Tools->Debugging->General->Enable .Net Framework Debugging
+
Tools->IntelliTace-> IntelliTaceEbents And Call Information
+
Tools->IntelliTace-> Set StorIntelliTace Recordings in this directory
and choose a directory
should allow you to step INTO .net code and trace every single function call.
I tried it on a small sample project and it works
after each debug session it suppose to create a recording of the debug session. it the set directory
even if CLR dies if im not mistaken
this should allow you to get to the extact call before CLR collapsed.
Try writing a generic exception handler and see if there is an unhandled exception killing your app.
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyExceptionHandler);
static void MyExceptionHandler(object sender, UnhandledExceptionEventArgs e) {
Console.WriteLine(e.ExceptionObject.ToString());
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
Environment.Exit(1);
I usually invesitgate memory related problems with Valgrind and gdb.
If you run your things on Windows, there are plenty of good alternatives such as verysleepy for callgrind as suggested here:
Is there a good Valgrind substitute for Windows?
If you really want to debug internal errors of the .NET runtime, you have the problem that there is no source for neither the class libraries nor the VM.
Since you can't debug what you don't have, I suggest that (apart from decompiling the .NET framework libraries in question with ILSpy, and adding them to your project, which still doesn't cover the vm) you could use the mono runtime.
There you have both the source of the class libraries as well as of the VM.
Maybe your program works fine with mono, then your problem would be solved, at least as long as it's only a one-time-processing task.
If not, there is an extensive FAQ on debugging, including GDB support
http://www.mono-project.com/Debugging
Miguel also has this post regarding valgrind support:
http://tirania.org/blog/archive/2007/Jun-29.html
In addition to that, if you let it run on Linux, you can also use strace, to see what's going on in the syscalls. If you don't have extensive winforms usage or WinAPI calls, .NET programs usually work fine on Linux (for problems regarding file system case-sensitivity, you can loopmount a case-insensitive file system and/or use MONO_IOMAP).
If you're Windows centric person, this post
says the closest thing Windows has is WinDbg's Logger.exe, but ltrace information is not as extensive.
Mono sourcecode is available here:
http://download.mono-project.com/sources/
You are probably interested in the sources of the latest mono version
http://download.mono-project.com/sources/mono/mono-3.0.3.tar.bz2
If you need framework 4.5, you'll need mono 3, you can find precompiled packages here
https://www.meebey.net/posts/mono_3.0_preview_debian_ubuntu_packages/
If you want to make changes to the sourcecode, this is how to compile it:
http://ubuntuforums.org/showthread.php?t=1591370
There are .NET exceptions which can not be caught. Check out: http://msdn.microsoft.com/en-us/magazine/dd419661.aspx.

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.
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.
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.
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):
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.
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.
Try to run this command
netsh winsock reset
Source: https://stackoverflow.com/a/20492181/1057791
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.
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);
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
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?
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.
Did you try turning off DEP (Data Execution Prevention) for your application ?
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.
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)
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...
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);
}
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.
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.
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.'
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.
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.
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 .
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)
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/
In some cases, this might happen when:
obj = new obj();
...
obj.Dispose(); // <----------------- Incorrect disposal causes it
obj.abc...
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.
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.
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.
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;
}
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.
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.

How should you diagnose the error SEHException - External component has thrown an exception

Whenever a user reports an error such as
System.Runtime.InteropServices.SEHException - External component has thrown an exception?
is there anything that I as a programmer can do to determine the cause?
Scenario : One user (using a program my company wrote) has reported this error.
This may or may not have been a one off error. They mentioned that in the last month, the computer has twice 'stopped working'. I have learnt from experience, not to take this description too literally, as it usually means that someone relating to the computer is not working as expected. They were unable to give me more details and I could not find any logged errors. Hence it may or may not have been this error.
From the stack-trace, the actual error was when constructing a class which does not directly call any interop code, but perhaps complicated by the fact that the object may be part of a list that is databound to a DevExpress Grid.
The error was 'caught' by an unhandled exception routine which normally will close down the program, but has an option to ignore and continue. If they opted to ignore the error, then the program continued working but the error re-occurred when this routine was next run. However it did not occur again after closing and restarting our application.
The computer in question did not seem to be stressed out. It is running Vista Business, has 2GB of memory and according to Task Manager was only using about half of that with our application just about 200Mb.
There is one other piece of information that may or may not be relevant. Another section of the same program uses a third party component which is effectively a dotnet wrapper around a native dll and this component does have a known issue where very occasionally, you get a
Attempted to read or write protected memory. This is often an indication that other memory is corrupt
The component makers say that this has been fixed in the latest version of their component which we are using in-house, but this has not been given to the customer yet.
Given that the consequences of the error are low (no work is lost and restarting the program and getting back to where they were only takes a minute at most) and given that the customer will shortly be getting a new version (with the updated third-party component), I can obviously cross my fingers and hope the error won't occur again.
But is there anything more I can do?
Yes. This error is a structured exception that wasn't mapped into a .NET error. It's probably your DataGrid mapping throwing a native exception that was uncaught.
You can tell what exception is occurring by looking at the ExternalException.ErrorCode property. I'd check your stack trace, and if it's tied to the DevExpress grid, report the problem to them.
I had a similar problem with an SEHException that was thrown when my program first used a native dll wrapper. Turned out that the native DLL for that wrapper was missing. The exception was in no way helpful in solving this. What did help in the end was running procmon in the background and checking if there were any errors when loading all the necessary DLLs.
if you are having a problem as describe in this post:
asp.net mvc debugger throwing SEHException
then the solution is:
if you have any application from Trusteer (like rapport or anything ) just uninstall and reboot your system, it'll work fine ... found this solution here:
http://forums.asp.net/t/1704958.aspx/8/10?Re+SEHException+thrown+when+I+run+the+application
The component makers say that this has been fixed in the latest version of their component which we are using in-house, but this has been given to the customer yet.
Ask the component maker how to test whether the problem that the customer is getting is the problem which they say they've fixed in their latest version, without/before deploying their latest version to the customer.
Just another information...
Had that problem today on a Windows 2012 R2 x64 TS system where the application was started from a unc/network path. The issue occured for one application for all terminal server users.
Executing the application locally worked without problems. After a reboot it started working again - the SEHException's thrown had been Constructor init and TargetInvocationException
I have come across this error when the app resides on a network share, and the device (laptop, tablet, ...) becomes disconnected from the network while the app is in use. In my case, it was due to a Surface tablet going out of wireless range. No problems after installing a better WAP.
My machine configurations :
Operating System : Windows 10 Version 1703 (x64)
I faced this error while debugging my C# .Net project in Visual Studio 2017 Community edition. I was calling a native method by performing p/invoke on a C++ assembly loaded at run-time. I encountered the very same error reported by OP.
I realized that Visual Studio was launched with a user account which was not an administrator on the machine. Then I relaunched Visual Studio under a different user account which was an administrator on the machine. That's all. My problem got resolved and I didn't face the issue again.
One thing to note is that the method which was being invoked on C++ assembly was supposed to write few things in registry. I didn't go debugging the C++ code to do some RCA but I see a possibility that the whole thing was failing as administrative privileges are required to write registry in Windows 10 operating system. So earlier when Visual Studio was running under a user account which didn't have administrative privileges on the machine, then the native calls were failing.
I got this error while running unit tests on inmemory caching I was setting up. It flooded the cache. After invalidating the cache and restarting the VM, it worked fine.

Categories