What is a canonical way to produce a segmentation fault in C#?

放肆的年华 提交于 2019-12-10 14:48:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!