tags:

views:

96

answers:

3

I am interested in the shortest, neatest piece of C# code around that will reliably produce a segfault - ideally without directly calling any unmanaged code.

A: 

Compile with csc with the /unsafe option:

class Program
{
    static void Main(string[] args)
    {
        unsafe
        {
            int *p = null;
            *p = 5;
        }
    }
}
Richard Cook
That actually throws a NullReferenceException, which is easy enough to get with plain old .NET. I'm assuming OP is after something more like an AccessViolationException.
Joe White
Under the covers an access violation (native exception code 0xC0000005) results from the null pointer dereference which is then trapped by the CLR and translated into an instance of `System.NullReferenceException`.
Richard Cook
A: 

As noted in the comments above, there's no such thing as a segfault in Windows, and you didn't say anything about mono on Linux. So I'm going to assume you actually meant an access violation.

Here's a way to get one:

unsafe {
    int* a = (int*) -4;
    *a = 0;
}

(Must be compiled with the /unsafe option.)

My first try used 0 as the address, but that turned out to throw a plain old NullReferenceException, which you can get without unsafe code. But the negative address gets an AccessViolationException on my Vista x64 box.

Joe White
Interestingly this results in `NullReferenceException` on Mono 1.9.1 running under Linux, so I guess it's architecture-dependent (or Mono gets it wrong!).
Richard Cook
Thanks. As far as terminology is concerned, I'm happy with calling an "access violation" a segfault - always have been.
Tom
+2  A: 

What you're after is somewhat unclear but I suppose this is as good as any answer so far, and it is about as minimal as you can get.

System.Runtime.InteropServices.Marshal.ReadInt32(IntPtr.Zero);

Michael Petito
Yes, thanks. That's what I was after.
Tom