问题
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.
回答1:
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);
回答2:
Michael's answer wasn't working for me, perhaps that case is caught now. Marshal.ReadInt32() just gives me a "SystemError: Attempted to read or write protected memory." with .NET 4.5 on Windows for various passed values. I used the following however which segfaults for me both on Windows and under mono 4.0.4.1:
using System.Runtime.InteropServices;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void UNMANAGED_CALLBACK();
public void Crash()
{
var crash = (UNMANAGED_CALLBACK)Marshal.GetDelegateForFunctionPointer((IntPtr) 123, typeof(UNMANAGED_CALLBACK));
crash();
}
回答3:
Compile with csc with the /unsafe option:
class Program
{
static void Main(string[] args)
{
unsafe
{
int *p = null;
*p = 5;
}
}
}
回答4:
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.
来源:https://stackoverflow.com/questions/3766122/what-is-a-canonical-way-to-produce-a-segmentation-fault-in-c