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
2010-09-22 03:54:12
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
2010-09-22 03:56:04
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
2010-09-22 03:57:51
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
2010-09-22 03:58:18
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
2010-09-22 04:01:24
Thanks. As far as terminology is concerned, I'm happy with calling an "access violation" a segfault - always have been.
Tom
2010-09-22 06:19:20
+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
2010-09-22 04:00:18