如何使用AccessViolationException使C#应用程序崩溃

Raf*_*Biz 5 c# access-violation

如何在C#中使用AccessViolationException故意使应用程序崩溃?

我有一个使用非托管DLL的控制台应用程序,该DLL最终由于访问冲突异常而崩溃。因此,AccessViolationException在某些情况下,我需要故意抛出一个,以测试其行为。

除此之外,它必须是专门的,AccessViolationException因为catch块不会处理此异常。

令人惊讶的是,这不起作用:

public static void Crash()
{
    throw new AccessViolationException();
}
Run Code Online (Sandbox Code Playgroud)

这都不是:

public static unsafe void Crash()
{
    for (int i = 1; true; i++)
    {
        var ptr = (int*)i;
        int value = *ptr;
    }
}
Run Code Online (Sandbox Code Playgroud)

Str*_*rom 5

确定性方法是让 Windows 为您抛出它:

从 ??????????? 的回答:如何使 C# 应用程序崩溃

[DllImport("kernel32.dll")]
static extern void RaiseException(uint dwExceptionCode, uint dwExceptionFlags,  uint nNumberOfArguments, IntPtr lpArguments);

void start()
{
    RaiseException(0xC0000005, 0, 0, new IntPtr(1));
}
Run Code Online (Sandbox Code Playgroud)


Ond*_*dar 2

这是“本机”方式 - 尽管 @Storm 方法是 100% 确定性的。技巧是尝试写入远离当前指针的内存。IE 即使我在程序中分配了 4 个字节,接下来的几千个字节仍然在为我的程序保留的内存部分内。远距离射击,你应该得到它。

int[] array = new int[1];
fixed (int* ptr = array)
{
      ptr[2000000] = 42;
}
Run Code Online (Sandbox Code Playgroud)