Write the shortest code that raises a Segmentation Fault (SIGSEGV) in any programming language.
- 52\$\begingroup\$ Wow. Possibly the shortest successful question. \$\endgroup\$Matthew Roh– Matthew Roh2017-02-09 11:42:53 +00:00Commented 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\$rydwolf– rydwolf ♦2020-11-21 20:38:20 +00:00Commented Nov 21, 2020 at 20:38
- \$\begingroup\$ @MatthewRoh And yet the question could be golfed further. "Raise a SIGSEGV. Code golf." \$\endgroup\$Steve Bennett– Steve Bennett2025-05-20 00:24:39 +00:00Commented May 20 at 0:24
- \$\begingroup\$ @MatthewRoh I now have a new contender :) codegolf.stackexchange.com/questions/281871/output-your-user-id \$\endgroup\$Steve Bennett– Steve Bennett2025-05-22 23:41:04 +00:00Commented May 22 at 23:41
86 Answers
Cython, 14
This often comes in handy for debugging purposes.
a=(<int*>0)[0] 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) - \$\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\$Florian Castellane– Florian Castellane2016-11-28 08:24:03 +00:00Commented 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\$Dennis Jaheruddin– Dennis Jaheruddin2016-11-29 16:13:12 +00:00Commented Nov 29, 2016 at 16:13
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 ;).
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.
- \$\begingroup\$ The
int i=*(int*)0;returns a NullReferenceException for me. \$\endgroup\$Peter Olson– Peter Olson2011-12-30 07:43:09 +00:00Commented Dec 30, 2011 at 7:43 - \$\begingroup\$ You can try to access a negative location, like
*(int*)-1=0and get an access violation. \$\endgroup\$Peter Olson– Peter Olson2011-12-30 07:46:59 +00:00Commented 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\$captncraig– captncraig2012-01-20 17:41:06 +00:00Commented Jan 20, 2012 at 17:41
- \$\begingroup\$ The reason why
*(int*)0=0throws an exception is likely due to optimization. Specifically, to avoid the cost of checking fornull, the optimizer may remove null checks, but when a segfault occurs it may rethrow it as a properNullReferenceException. \$\endgroup\$null– null2018-09-15 20:55:43 +00:00Commented Sep 15, 2018 at 20:55
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.
J (6)
memf 1 memf means free memory, 1 is interpreted as a pointer.
- \$\begingroup\$ Why
1rather than0? Is it legal to free a null pointer in J? \$\endgroup\$Sapphire_Brick– Sapphire_Brick2020-11-18 18:35:26 +00:00Commented Nov 18, 2020 at 18:35
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.
Python 3.8, 14 bytes
This only works on Python 3.8 :P. I found this while scavenging bug reports.
*reversed({}), 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
- \$\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\$tomsmeding– tomsmeding2016-12-16 19:55:36 +00:00Commented 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\$Downgoat– Downgoat2016-12-16 19:56:39 +00:00Commented Dec 16, 2016 at 19:56
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);}} 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
- \$\begingroup\$ It does the same as the Dyvil Answer below \$\endgroup\$Serverfrog– Serverfrog2017-02-09 14:51:56 +00:00Commented 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\$mbomb007– mbomb0072017-02-09 14:58:39 +00:00Commented 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\$Serverfrog– Serverfrog2017-02-09 15:07:28 +00:00Commented Feb 9, 2017 at 15:07
- 2\$\begingroup\$ Why the long names and
import x.y.asdf;instead ofimport x.y.*;? \$\endgroup\$MercyBeaucou– MercyBeaucou2017-02-14 04:36:13 +00:00Commented Feb 14, 2017 at 4:36 - 1\$\begingroup\$ Using
java.lang.reflect.Constructorinstead of importing it saves 9 bytes \$\endgroup\$Poke– Poke2017-05-01 17:16:26 +00:00Commented May 1, 2017 at 17:16
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.
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.
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.
Lua (LuaJIT), 47 43 bytes
f=require"ffi"f.cdef"int puts()"f.C.puts() Uses FFI in LuaJIT to call puts() with no (valid) argument.
Ruby, 15 bytes
eval a='eval a' Segfaults (Ruby 2.3 on Ubuntu xenial)
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.)
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.
Clean, 19 12 bytes
Start=code{} 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.
- 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, aStartnode 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_spineis then filled. But because it doesn't, thefill_ainstruction then attempts to fill an uninitialised node above_cycle_in_spine. \$\endgroup\$user42682– user426822019-01-08 10:51:43 +00:00Commented 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\$Οurous– Οurous2019-01-08 16:03:19 +00:00Commented Jan 8, 2019 at 16:03
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(!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2MLKJIH+dv'Ps$_"]~[|YzWxUvStQrOpMnKlIjGhEfCAAyxw`;zLxwpo#F!~joQmPNd<hKJr^GoEm~B@zzy,X;c(s&5QJmNGL.h-yTdEc=`;$LK=m|:FV7Cwe3craq_'J\H)jF&%B0/RQ Rust, 38 33 bytes
unsafe{*(std::ptr::null_mut())=0} 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();} - 1\$\begingroup\$ There is something slightly poetic about a segfault in Rust \$\endgroup\$2020-11-21 20:45:11 +00:00Commented Nov 21, 2020 at 20:45
Jelly, 2 bytes
ßß 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 ß.
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.
- 1\$\begingroup\$ Under Linux,
cliandstiwill segfault all by themselves, because they're privileged, not because of the lack of exit point. You could addhltto the list for the same reason. \$\endgroup\$Nate Eldredge– Nate Eldredge2020-12-09 19:33:35 +00:00Commented Dec 9, 2020 at 19:33 - \$\begingroup\$ @NateEldredge Isn't
hltthe opcode for "halt"?hltcauses 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\$Sapphire_Brick– Sapphire_Brick2020-12-09 23:42:05 +00:00Commented Dec 9, 2020 at 23:42 - 2\$\begingroup\$ Yes,
hltwill 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.cliandstiare in a similar boat, though the privilege requirements are more complicated. \$\endgroup\$Nate Eldredge– Nate Eldredge2020-12-09 23:49:50 +00:00Commented Dec 9, 2020 at 23:49 - \$\begingroup\$ @NateEldredge Ok, I've updated this answer. \$\endgroup\$Sapphire_Brick– Sapphire_Brick2020-12-10 00:02:35 +00:00Commented Dec 10, 2020 at 0:02
C++ (clang), compiler crash, 36 28 bytes
class{operator*(...){*this*1 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 " Found this bug when golfing the assembly here
Note that this bug seems to have been fixed as of v2.34.
Rust, 17 bytes
fn main(){main()} Well... This just calls itself. It may be the only way to do it without unsafe.
- \$\begingroup\$ It looks like Rust actually detects the stack overflow and aborts.. What version are you running? 🤔 \$\endgroup\$EasyasPi– EasyasPi2021-02-11 01:24:58 +00:00Commented Feb 11, 2021 at 1:24
- \$\begingroup\$ But, it also is doing segfault, before aborting... as I found with
strace\$\endgroup\$SuperPizz– SuperPizz2021-02-11 01:27:26 +00:00Commented Feb 11, 2021 at 1:27 - \$\begingroup\$ Oh, I guess you're right. My bad. Good find, then! \$\endgroup\$EasyasPi– EasyasPi2021-02-11 01:44:45 +00:00Commented Feb 11, 2021 at 1:44
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>vL<^e()j!o&rx~2
All of these attempt to perform some operation on an empty stack. Interestingly, , (pop from stack) runs just fine (though it loops forever).
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 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) 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] Okay, this one's actually kinda wonky.
- If the generic parameter to
UnsafePointerisInt, 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:)returnsnilfor an argument of0, 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]() Escapes a pointer to a closure, wraps it in an array to add some indirection, then tries to call the closure via the pointer.
Perl 6, 22
shell "kill -11 $*PID" Just shelling to whatever shell you have.
- 2\$\begingroup\$ Why not do it directly in bash (11 chars):
kill -11 $$... \$\endgroup\$Elist– Elist2017-02-18 20:55:57 +00:00Commented Feb 18, 2017 at 20:55
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 - 2\$\begingroup\$ You can use
m@main=m>>m\$\endgroup\$H.PWiz– H.PWiz2018-09-02 00:08:14 +00:00Commented Sep 2, 2018 at 0:08 - \$\begingroup\$ I don't know about you, but I just get a SIGKILL. \$\endgroup\$Sapphire_Brick– Sapphire_Brick2020-12-25 20:15:58 +00:00Commented Dec 25, 2020 at 20:15