123
\$\begingroup\$

Write the shortest code that raises a Segmentation Fault (SIGSEGV) in any programming language.

\$\endgroup\$
4
  • 52
    \$\begingroup\$ Wow. Possibly the shortest successful question. \$\endgroup\$ Commented Feb 9, 2017 at 11:42
  • 6
    \$\begingroup\$ @MatthewRoh Out of interest, I made this SEDE query. It looks like there are a few with +10 or higher, but this is the first above +40 \$\endgroup\$ Commented Nov 21, 2020 at 20:38
  • \$\begingroup\$ @MatthewRoh And yet the question could be golfed further. "Raise a SIGSEGV. Code golf." \$\endgroup\$ Commented May 20 at 0:24
  • \$\begingroup\$ @MatthewRoh I now have a new contender :) codegolf.stackexchange.com/questions/281871/output-your-user-id \$\endgroup\$ Commented May 22 at 23:41

86 Answers 86

6
\$\begingroup\$

Cython, 14

This often comes in handy for debugging purposes.

a=(<int*>0)[0] 
\$\endgroup\$
6
\$\begingroup\$

Matlab - Yes it is possible!

In a response to a question of mine, Amro came up with this quirk:

S = struct(); S = setfield(S, {}, 'g', {}, 0) 
\$\endgroup\$
2
  • \$\begingroup\$ Please give Matlab version -- R2015B (and 2016B also) just throws an error: Error using setfield (line 56) At least one index is required. \$\endgroup\$ Commented Nov 28, 2016 at 8:24
  • \$\begingroup\$ @FlorianCastellane Not able to try all versions now, but it has been confirmed to give a segfault in quite some versions, the latest being 2014b and the earliest 2012a. \$\endgroup\$ Commented Nov 29, 2016 at 16:13
6
\$\begingroup\$

Rust, 34 bytes

fn main(){unsafe{*(0 as*mut _)=3}} 

Just a null pointer assignment, nothing special here.


As a bonus, 45 44 40 bytes solution not using unsafe. Arguably a bug in a compiler.

#![no_main]#[no_mangle]static main:i8=0; 

Main is usually a function ;).

\$\endgroup\$
0
6
\$\begingroup\$

C# - 62

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

C# /unsafe, 23 bytes

unsafe{int i=*(int*)0;} 

For some reason I don't understand, *(int*)0=0 just throws a NullReferenceException, while this version gives the proper access violation.

\$\endgroup\$
4
  • \$\begingroup\$ The int i=*(int*)0; returns a NullReferenceException for me. \$\endgroup\$ Commented Dec 30, 2011 at 7:43
  • \$\begingroup\$ You can try to access a negative location, like *(int*)-1=0 and get an access violation. \$\endgroup\$ Commented Dec 30, 2011 at 7:46
  • \$\begingroup\$ The particular exception is just what the clr wraps it in, and is insignificant. The os itself actually gives the seg fault in all these cases. \$\endgroup\$ Commented Jan 20, 2012 at 17:41
  • \$\begingroup\$ The reason why *(int*)0=0 throws an exception is likely due to optimization. Specifically, to avoid the cost of checking for null, the optimizer may remove null checks, but when a segfault occurs it may rethrow it as a proper NullReferenceException. \$\endgroup\$ Commented Sep 15, 2018 at 20:55
6
\$\begingroup\$

Ruby 3.x, 10 bytes

->x=(1in^x 

Ruby doesn't like a circular pin reference in proc argument for some reason, this results in a null pointer dereference. Since this is a parser bug the program doesn't even have to be syntactically valid.

\$\endgroup\$
5
\$\begingroup\$

J (6)

memf 1 

memf means free memory, 1 is interpreted as a pointer.

\$\endgroup\$
1
  • \$\begingroup\$ Why 1 rather than 0? Is it legal to free a null pointer in J? \$\endgroup\$ Commented Nov 18, 2020 at 18:35
5
\$\begingroup\$

Unix PDP-11 assembly, 18 bytes binary, 7 bytes source

(this is becoming a theme with me, maybe because it's the only language I sort of know that no-one else here does.)

inc(r0) 

Increments the single byte addressed by the initial value of r0 [which happens to be 05162 according to the simh debugger] as of program start.

0000000 000407 000002 000000 000000 000000 000000 000000 000000 0000020 005210 000000 

And, as always, the extraneous bytes at the end can be removed with strip.

I made a few attempts to get the source shorter, but always ended up getting either a syntax error or SIGBUS.

\$\endgroup\$
5
\$\begingroup\$

Python 3.8, 14 bytes

This only works on Python 3.8 :P. I found this while scavenging bug reports.

*reversed({}), 

Try it online!

\$\endgroup\$
4
\$\begingroup\$

JavaScript Shell, 7 bytes

clear() 

Clears absolutely everything, not just the current scope which obviously causes lots of borks which result in JS blowing up and segfaulting

\$\endgroup\$
2
  • \$\begingroup\$ According to MDN (document.clear), this should only do something in really old versions of Mozilla, and even then, what really segfaults in your experience? \$\endgroup\$ Commented Dec 16, 2016 at 19:55
  • \$\begingroup\$ @tomsmeding this is window.clear, FF directly doesn't reveal it, it's a spidermonkey built-in \$\endgroup\$ Commented Dec 16, 2016 at 19:56
4
\$\begingroup\$

Java (OpenJDK 9), 311 227 223 bytes

import sun.misc.*;import java.lang.reflect.*;class M{public static void main(String[]args) throws Exception{Constructor<Unsafe> c=Unsafe.class.getDeclaredConstructor();c.setAccessible(true);c.newInstance().getAddress(0);}} 

Try it online!

Ungolfed:

import sun.misc.Unsafe; import java.lang.reflect.Constructor; public class SegFault { public static void main(String[] args) throws Exception { Constructor<Unsafe> unsafeConstructor = Unsafe.class.getDeclaredConstructor(); unsafeConstructor.setAccessible(true); Unsafe unsafe = unsafeConstructor.newInstance(); System.out.println(unsafe.getAddress(0)); } } 

Saved 84 Bytes thanks to Mistah Figg

\$\endgroup\$
9
  • \$\begingroup\$ It does the same as the Dyvil Answer below \$\endgroup\$ Commented Feb 9, 2017 at 14:51
  • \$\begingroup\$ Ask the OP. After searching, I think Access Violation and SegFault are maybe two names for the same thing. \$\endgroup\$ Commented Feb 9, 2017 at 14:58
  • \$\begingroup\$ TIO throws a SIGSEGV on OpenJDK, so I think its Possible that Oracle and OpenJDK throws same things but under different names. \$\endgroup\$ Commented Feb 9, 2017 at 15:07
  • 2
    \$\begingroup\$ Why the long names and import x.y.asdf; instead of import x.y.*; ? \$\endgroup\$ Commented Feb 14, 2017 at 4:36
  • 1
    \$\begingroup\$ Using java.lang.reflect.Constructor instead of importing it saves 9 bytes \$\endgroup\$ Commented May 1, 2017 at 17:16
4
\$\begingroup\$

Befunge-98 (FBBI), 1 byte

= 

Try it online! (expand the Debug section to view the segfault)

This only works in the FBBI implementation of Befunge, exploiting a bug in its string handling code. Any attempt to read a string from an empty stack will result in a null pointer dereference. You can achieve the same result with the i (Input File) and o (Output File) instructions, which also expect a string on the stack.

Note that this error wouldn't occur if the stack was simply full of zeros, which in Befunge should be semantically equivalent to an empty stack. For it to crash the stack must be genuinely empty, as is the case on startup.

\$\endgroup\$
4
\$\begingroup\$

Tcl, 60 bytes

set a a;while {[incr i]<999999999} {set a [list $a]};puts $a 

Not short, but crashes with a segfault.

This builds a deeply nested list (each with only one element), and when trying to serialize it, Tcl will crash with a stack overflow.

I have reported this bug here

\$\endgroup\$
4
\$\begingroup\$

AArch64, 4 bytes

Raw machine code:

d65f03e0 

Disassembly

 .globl f f: ret xzr 

Branches to the xzr register, which is always null. We can't do something like str x0, [xzr] because it would be treated as sp.

\$\endgroup\$
4
+100
\$\begingroup\$

Lua (LuaJIT), 47 43 bytes

f=require"ffi"f.cdef"int puts()"f.C.puts() 

Try it online!

Uses FFI in LuaJIT to call puts() with no (valid) argument.

\$\endgroup\$
3
\$\begingroup\$

Ruby, 15 bytes

eval a='eval a' 

Segfaults (Ruby 2.3 on Ubuntu xenial)

\$\endgroup\$
3
\$\begingroup\$

Lua (luajit), 52 48 bytes

function f()c=coroutine;c.resume(c.create(f))end 

An attempt to compete for the bounty that was recently set on an answer in Lua. This is a function submission (basically because I had to define a function anyway, so not including the code to run it saves bytes). Now with 4 bytes saved due to a suggestion by @ceilingcat to avoid repeating the word coroutine.

The program works by creating infinitely many coroutines, suspending each in turn to create and start the next. The most commonly used Lua interpreter, lua, thought of this case and starts causing coroutine creation to fail after a while. luajit, however, segfaults. (Valgrind reports the issue as a failure to grow the OS-defined stack; this is believable, seeing as one common coroutine implementation gives them each separate parts of the stack.)

\$\endgroup\$
0
3
\$\begingroup\$

Lua 5.3.2 PUC-RIO (the "official") interpreter - 57 bytes

local t={}t.__newindex=t local y=setmetatable({},t)y[1]=1 

Note: does not work on all machines, and was fixed in Lua 5.3.3.

\$\endgroup\$
3
\$\begingroup\$

Clean, 19 12 bytes

Start=code{} 

Try it online!

Every function always returns something in Clean, including Start. Because we haven't specified the type of Start, the compiler assumes (and it can only assume when you inline ABC) that it takes no arguments. Since it takes no arguments, there's nothing on either stack when the function resolves, and so the runtime tries to evaluate the first node in the spine of a graph with... Zero nodes.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Nice, but the explanation is not entirely correct. The compiler knows the arity by the number of arguments of Start; there is no way to write a function in ABC that takes a number of arguments other than the number of arguments of the Clean function. On startup, a Start node is created. When it is evaluated, it is overwritten by _cycle_in_spine. The ABC code is supposed to push a new node on the stack, with which the _cycle_in_spine is then filled. But because it doesn't, the fill_a instruction then attempts to fill an uninitialised node above _cycle_in_spine. \$\endgroup\$ Commented Jan 8, 2019 at 10:51
  • \$\begingroup\$ @Keelan I learn something new every time you comment :). I'll edit that in once I'm back at my computer. \$\endgroup\$ Commented Jan 8, 2019 at 16:03
3
\$\begingroup\$

Malbolge, 3046 bytes

Behold, an answer in Malbolge that you can embed inside an answer!

bP&A@?>=<;:9876543210/.-,+*)('&%$T"!~}|;]yxwvutslUSRQ.yx+i)J9edFb4`_^]\yxwRQ)(TSRQ]m!G0KJIyxFvDa%_@?"=<5:98765.-2+*/.-,+*)('&%$#"!~}|utyrqvutsrqjonmPkjihgfedc\DDYAA\>>Y;;V886L5322G//D,,G))>&&A##!7~5:{y7xvuu,10/.-,+*)('&%$#"yb}|{zyxwvutmVqSohmOOjihafeHcEa`YAA\[ZYRW:U7SLKP3NMLK-I,GFED&%%@?>=6;|9y70/4u210/o-n+k)"!gg$#"!x}`{zyxZvYtsrqSoRmlkjLhKfedcEaD_^]\>Z=XWVU7S6QPON0LKDI,GFEDCBA#?"=};438y6543s1r/o-&%*k('&%e#d!~}|^z]xwvuWsVqponPlOjihgIeHcba`B^A\[ZY;W:UTSR4PI2MLKJ,,AFE(&B;:?"~<}{zz165v3s+*/pn,mk)jh&ge#db~a_{^\xwvoXsrqpRnmfkjMKg`_GG\aDB^A?[><X;9U86R53ONM0KJC,+FEDC&A@?!!6||3876w4-tr*/.-&+*)('&%$e"!~}|utyxwvutWlkponmlOjchg`edGba`_XW\?ZYRQVOT7RQPINML/JIHAFEDC&A@?>!<;{98yw5.-ss*/pn,+lj(!~ff{"ca}`^z][wZXtWUqTR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YzWxUvStQrOpMnKlIjGhEfCAAyxw`;zLxwpo#F!~joQmPNd<hKJr^GoEm~B@zzy,X;c(s&5QJmNGL.h-yTdEc=`;$LK=m|:FV7Cwe3craq_'J\H)jF&%B0/RQ 

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Rust, 38 33 bytes

unsafe{*(std::ptr::null_mut())=0} 

Try it online!

Full program is fn main(){...}. Segfaults as setting a null pointer to a type is undefined behavior (hence the unsafe block that is required). Old version:

unsafe{std::ptr::null::<u8>().read();} 
\$\endgroup\$
1
  • 1
    \$\begingroup\$ There is something slightly poetic about a segfault in Rust \$\endgroup\$ Commented Nov 21, 2020 at 20:45
3
\$\begingroup\$

Jelly, 2 bytes

ßß 

Try it online!

oh

Since ß isn't actually coded as a recursive function call in the underlying Python, it isn't affected by the recursion limit. I don't actually know how Jelly's quicks work under the hood, but this appears to just create a nested structure that grows until it can't anymore. Any atom or atom-like quick works after the first ß.

\$\endgroup\$
3
\$\begingroup\$

NASM, 3 characters.

any of the following:

ret nop cbw cwd cdq clc cld cli cmc aaa aas aad aam stc std sti 

ret causes stack underflow. cli and sti trigger SIGSEGV because they are privileged instructions. All the other opcodes trigger a SIGSEGV simply because there's no exit point.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Under Linux, cli and sti will segfault all by themselves, because they're privileged, not because of the lack of exit point. You could add hlt to the list for the same reason. \$\endgroup\$ Commented Dec 9, 2020 at 19:33
  • \$\begingroup\$ @NateEldredge Isn't hlt the opcode for "halt"? hlt causes the program to segfault, and does not halt the processor, even though the NASM manual (posix.nl/linuxassembly/nasmdochtml/nasmdoca.html#section-A.74) says it does. \$\endgroup\$ Commented Dec 9, 2020 at 23:42
  • 2
    \$\begingroup\$ Yes, hlt will halt the processor if executed at privilege level 0, but if not then it raises a general protection fault. See for instance felixcloutier.com/x86/hlt. Linux userspace programs are at privilege level 3, and the kernel handles the GPF by delivering SIGSEGV to the process. cli and sti are in a similar boat, though the privilege requirements are more complicated. \$\endgroup\$ Commented Dec 9, 2020 at 23:49
  • \$\begingroup\$ @NateEldredge Ok, I've updated this answer. \$\endgroup\$ Commented Dec 10, 2020 at 0:02
3
\$\begingroup\$

C++ (clang), compiler crash, 36 28 bytes

class{operator*(...){*this*1 

Try it online!

Unlike the other compiler crash which I found on my own, I totally didn't look this one up on bugs.llvm.org..

Assembly (as, x64, Linux), 17 10 bytes

Unfortunately, this was not a segfault, but an assertion. Leaving it up with another compiler segfault as a bonus.

I wrote code that raises a SIGSEGV in assembler.

Literally. 😏

Replace \0 with a literal 0x00 byte.

"\0.asciz " 

Try it online!

Found this bug when golfing the assembly here

Note that this bug seems to have been fixed as of v2.34.

\$\endgroup\$
3
\$\begingroup\$

Rust, 17 bytes

fn main(){main()} 

Try it online!

Well... This just calls itself. It may be the only way to do it without unsafe.

\$\endgroup\$
3
3
\$\begingroup\$

Trilangle, UB, 1 byte

If you allow undefined behavior that happens to segfault on my machine (Windows 10 on x64), all of the following programs work:

  • +
  • -
  • *
  • :
  • %
  • 7
  • >
  • v
  • L
  • <
  • ^
  • e
  • (
  • )
  • j
  • !
  • o
  • &
  • r
  • x
  • ~
  • 2

All of these attempt to perform some operation on an empty stack. Interestingly, , (pop from stack) runs just fine (though it loops forever).

\$\endgroup\$
3
\$\begingroup\$

Swift 6.1.2, 36 11 bytes

let x:Any=x 

Try it on SwiftFiddle! (The Any type annotation is required.)

I'm 99% sure this only works due to a compiler bug, because last time I checked Swift really isn't supposed to let you do this.

Other interesting segfaults (sorted by length)

Stack overflow (13 bytes)

var x:(){x} x 

Try it on SwiftFiddle!

Declares a computed variable (of type (), aka Void) that accesses itself, then tries to access the variable. (Swift is smart enough to warn you about this. Twice.)

Suicide (22 bytes on Linux, 23 bytes on macOS)

import Glibc raise(11) 

Try it on SwiftFiddle!

Fairly self-explanatory. Replace Glibc with Darwin if running on macOS.

Deinit abuse (24 bytes)

class C{deinit{C()}} C() 

Try it on Compiler Explorer! (SwiftFiddle doesn't finish backtracing)

This ends up recursively calling _swift_release_dealloc in the runtime, ending with a stack overflow.

"Null" pointer dereference (36 bytes)

UnsafePointer<Any>(bitPattern:1)![0] 

Try it on SwiftFiddle!

Okay, this one's actually kinda wonky.

  • If the generic parameter to UnsafePointer is Int, this doesn't segfault.
  • But if the whole thing's wrapped in a call to print, it always segfaults (regardless of the generic parameter).
  • UnsafePointer.init?(bitPattern:) returns nil for an argument of 0, but if you give it any other value, it will happily return an invalid pointer.

Use-after-free (38 bytes)

[withUnsafePointer(to:{}){$0}][0][0]() 

Try it on SwiftFiddle!

Escapes a pointer to a closure, wraps it in an array to add some indirection, then tries to call the closure via the pointer.

\$\endgroup\$
2
\$\begingroup\$

Perl 6, 22

shell "kill -11 $*PID" 

Just shelling to whatever shell you have.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Why not do it directly in bash (11 chars): kill -11 $$... \$\endgroup\$ Commented Feb 18, 2017 at 20:55
2
\$\begingroup\$

Dyvil, 42 bytes

dyvil.reflect.ReflectUtils.UNSAFE.getInt 0 

Explanation:

dyvil.reflect.ReflectUtils // qualified type name .UNSAFE // accesses the static field UNSAFE in class // dyvil.reflect.ReflectUtils, of type sun.misc.Unsafe .getInt 0 // calls the method sun.misc.Unsafe.getInt(long), // which tries to read a 4-byte integer from // the memory address 0 
\$\endgroup\$
2
\$\begingroup\$

Whispers, 5 bytes

>> 1! 

Try it online!

How it works

>> 1 - Call this line repeated ! - Prevent tail call 
\$\endgroup\$
2
\$\begingroup\$

Haskell, 15 bytes

Causes a stackoverflow:

main=main>>main 

Try it online!

\$\endgroup\$
2
  • 2
    \$\begingroup\$ You can use m@main=m>>m \$\endgroup\$ Commented Sep 2, 2018 at 0:08
  • \$\begingroup\$ I don't know about you, but I just get a SIGKILL. \$\endgroup\$ Commented Dec 25, 2020 at 20:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.