Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 681
Tom Avatar asked Sep 22 '10 03:09

Tom


2 Answers

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);

like image 124
Michael Petito Avatar answered Nov 13 '22 00:11

Michael Petito


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();
    }
like image 20
David Evans Avatar answered Nov 13 '22 00:11

David Evans