Common causes of - Access Violation errors under .

2020-06-03 11:19发布

问题:

I'm looking for common causes of Access Violation errors under .NET.

Things I have checked so far -

  • Call Dispose on all objects implementing IDisposable
  • Check for valid arguments in calls to COM objects
  • Explicitly remove all manually added event handlers
  • DO NOT explicity call GC.Collect/GC.WaitForPendingFinalizers
  • Add and Remove memory pressure when dealing with native objects (Bitmap, etc..) (Added)
  • Verify all PInvoke calls for valid argument types
  • Ensure proper use of IntPtr, SafeHandle and HandleRef
  • Threading (Thread Safe, Reentrant functions), proper use of waithandles. (Added)
  • Ensure application and DLL's are all targetting the same platform (x86 or x64) (The application and dll's should target the same platform as the COM objects.) (Added)

Any other suggestions?

Edit - Moved crash dump analysis to different question.

回答1:

Any use of unsafe or unmanaged code can get you that type of exceptions.

AccessViolationException:

An access violation occurs in unmanaged or unsafe code when the code attempts to read or write to memory that has not been allocated, or to which it does not have access. This usually occurs because a pointer has a bad value. Not all reads or writes through bad pointers lead to access violations, so an access violation usually indicates that several reads or writes have occurred through bad pointers, and that memory might be corrupted. Thus, access violations almost always indicate serious programming errors. In the .NET Framework version 2.0, an AccessViolationException clearly identifies these serious errors.

In programs consisting entirely of verifiable managed code, all references are either valid or null, and access violations are impossible. An AccessViolationException occurs only when verifiable managed code interacts with unmanaged code or with unsafe managed code.

Recommended:

GFlags and Application Verifier



回答2:

Are you generating IL at runtime or using a component which does so? Using unsafe C# code, doing pointer manipulation?