CLR 4.0 拾遗系列1.1 System.AccessViolationException
Namespace:
Class:
System.AccessViolationException
Remarks:
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.
Samples:
using System; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; class Program { [DllImport("ole32.dll")] public static extern UInt32 StgCreateStorageEx( [MarshalAs(UnmanagedType.LPWStr), In] string pwcsName, long grfMode, //TODO grfMode should have been an int not a long int stgfmt, uint grfAttrs, [In] IntPtr pStgOptions, [In] IntPtr reserved2, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out object ppObjectOpen ); public const int STGM_READWRITE = 0x00000002; public const int STGM_SHARE_EXCLUSIVE = 0x00000010; public const int STGFMT_STORAGE = 0; [HandleProcessCorruptedStateExceptions] static void Main(string[] args) { try { IntPtr ptr2ptr2ptr = Marshal.AllocHGlobal(IntPtr.Size); IntPtr ptr2ptr = Marshal.AllocHGlobal(IntPtr.Size); IntPtr ptr2data = Marshal.AllocHGlobal(104857600); Marshal.WriteIntPtr(ptr2ptr, ptr2data); Marshal.WriteIntPtr(ptr2ptr2ptr, ptr2ptr); Guid IID_IStorage = new Guid("0000000B-0000-0000-C000-000000000046"); UInt32 results; object ppObjectOpen; results = StgCreateStorageEx(null, STGM_READWRITE + STGM_SHARE_EXCLUSIVE, STGFMT_STORAGE, 0, IntPtr.Zero, IntPtr.Zero, ref IID_IStorage, out ppObjectOpen); } catch (AccessViolationException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } }
References: