views:

879

answers:

2

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.

A: 

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

SDX2000
@SDX2000 - Good thinking. Thanks for the suggestions.
You are welcome.
SDX2000
+1  A: 

Hi,

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

Ric Tokyo
Yup, that defines it well. Do you have suggestions as to what to look for in your .NET code to help prevent or track down these types of errors?
Hi, sure, Edited the answer to include those (GFlags and Application verifier)
Ric Tokyo