Search code examples
c#access-violation

How to make C# application crash with an AccessViolationException


How to intentionally crash an application with an AccessViolationException in c#?

I have a console application that use an unmanaged DLL that eventually crashes because of access violation exceptions. Because of that, I need to intentionally throw an AccessViolationException to test how it behaves under certain circumstances.

Besides that, it must be specifically an AccessViolationException because this exception is not handled by the catch blocks.

Surprisingly, this does not work:

public static void Crash()
{
    throw new AccessViolationException();
}

Neither this:

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

Solution

  • This is the "native" way - although the @Storm approach is 100% deterministic. Trick is to attempt to write into memory far away from the current pointer. I.E. even though I allocated 4 bytes in my program, the next few thousand bytes are still within the part of memory reserved for my program. Shoot far away and you should get it.

    int[] array = new int[1];
    fixed (int* ptr = array)
    {
          ptr[2000000] = 42;
    }