Troubleshooting Exceptions: System.AccessViolationException

 

An AccessViolationException is thrown when there is an attempt to read from or write to protected memory.

Associated Tips

  • Make sure that the memory that you are attempting to access has been allocated.
    Automatic memory management is one of the services that the common language runtime provides. You may wish to move to managed code to take advantage of this service. For more information, see Automatic Memory Management.

  • Make sure that the memory that you are attempting to access has not been corrupted.
    If several read or write operations have occurred through bad pointers, memory may be corrupted.

Remarks

An access violation occurs in unmanaged or unsafe code when it attempts to read or write to memory that has not been allocated, or to which it does not have access. 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.

In managed code, all references are either valid or null. Any operation that attempts to reference a null reference in verifiable code throws NullReferenceException.

An access violation that occurs in unsafe managed code can be expressed as either a NullReferenceException or a AccessViolationException, depending on the platform.

Access violations in unmanaged code that bubble up to managed code are always wrapped in an AccessViolationException.

See Also

How to: Use the Exception Assistant
Memory Management: Examples
Automatic Memory Management