Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 342
Rafael Biz Avatar asked May 30 '19 21:05

Rafael Biz


People also ask

How do I create a C file?

To write a C code file in Notepad, type your C code into a blank page in the text editor, and then save the file with a ". c" file extension if the file consists of a C code page, or the ". h" file extension if the file consists of header code.

What is the Makefile in C?

Makefile is a set of commands (similar to terminal commands) with variable names and targets to create object file and to remove them. In a single make file we can create multiple targets to compile and to remove object, binary files. You can compile your project (program) any number of times by using Makefile.


1 Answers

A Deterministic approach is to have Windows throw it for you:

From Петър Петров's answer to: How to make C# application crash

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

void start()
{
    RaiseException(0xC0000005, 0, 0, new IntPtr(1));
}
like image 57
Strom Avatar answered Nov 14 '22 23:11

Strom