75
\$\begingroup\$

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

\$\endgroup\$
  • 30
    \$\begingroup\$ Wow. Possibly the shortest successful question. \$\endgroup\$ – Matthew Roh Feb 9 '17 at 11:42

52 Answers 52

113
\$\begingroup\$

C, 5 characters

main;

It's a variable declaration - int type is implied (feature copied from B language) and 0 is default value. When executed this tries to execute a number (numbers aren't executable), and causes SIGSEGV.

Try it online!

\$\endgroup\$
  • 5
    \$\begingroup\$ @Macmade: Actually, it is 0. static variables start as 0, and main; is static, as I declared it outside function. c-faq.com/decl/initval.html \$\endgroup\$ – Konrad Borowski Aug 16 '13 at 8:20
  • 16
    \$\begingroup\$ last time i played with this thing, i figured out that there's a different reason for the segfault. First of all by calling main you jump to the location of main, not the value, another thing is main is an int, it's located in .bss, usually functions are located in .text, when the kernel loads the elf program it creates an executable page for .text and non-executable for .bss, so by calling main, you jump to a non-executable page, and execution something on a such page is a protection fault. \$\endgroup\$ – mniip Dec 6 '13 at 17:55
  • 23
    \$\begingroup\$ Yep, segfaults in C are pretty much the default :P \$\endgroup\$ – Paul Draper May 24 '14 at 23:23
  • 1
    \$\begingroup\$ main __attribute__((section(".text#")))=0xc3; FTFY (at least it seems to return without crashing on my x86). \$\endgroup\$ – jozxyqk Jul 27 '18 at 4:57
  • 2
    \$\begingroup\$ @jozxyqk Or shorter, const main=195;. As interesting it is that it's working, the goal of this code golfing challenge was to make the code segfault, not work :). \$\endgroup\$ – Konrad Borowski Jul 27 '18 at 6:48
74
\$\begingroup\$

Bash, 11      

kill -11 $$
\$\endgroup\$
  • 44
    \$\begingroup\$ Signal 11 in 11 characters. Seems legit. \$\endgroup\$ – nyuszika7h Dec 31 '13 at 12:39
  • 12
    \$\begingroup\$ @nyuszika7h I was going to upvote your comment, but you have 11 upvotes right now, so I'm going to leave it at that. :P \$\endgroup\$ – HyperNeutrino Nov 25 '16 at 16:22
  • 3
    \$\begingroup\$ @AlexL. other people seem to have spoiled that :( \$\endgroup\$ – theonlygusti Jan 21 '17 at 10:51
  • 2
    \$\begingroup\$ @theonlygusti Yeah... That's too bad. :( Oh well, then I can upvote it now. \$\endgroup\$ – HyperNeutrino Jan 21 '17 at 14:27
  • 2
    \$\begingroup\$ Up to 42 upvotes, no touchee! \$\endgroup\$ – seadoggie01 Sep 3 '18 at 15:24
39
\$\begingroup\$

Assembly (Linux, x86-64), 1 byte

RET

This code segfaults.

\$\endgroup\$
  • 7
    \$\begingroup\$ As an MSDOS .com file, it runs and terminates without error. \$\endgroup\$ – J B Dec 26 '11 at 19:10
  • 10
    \$\begingroup\$ My point being: just specifying “assembly” isn't enough to make it segfault. \$\endgroup\$ – J B Dec 26 '11 at 19:56
  • 52
    \$\begingroup\$ @JB: On MS DOS, no program will ever produce a segmentation fault. That's because MS DOS runs in real mode where memory protection is nonexistent. \$\endgroup\$ – celtschk Feb 4 '12 at 17:25
  • 1
    \$\begingroup\$ @celtschk IIRC NTVDM will eke out on nonexistent addresses, and those not allocated to MS-DOS. \$\endgroup\$ – ζ-- Jan 31 '13 at 1:32
  • 2
    \$\begingroup\$ @celtschk: You can segfault it anyway like so: mov bx, 1000h ; shr ebx, 4 ; mov eax, [ebx] -> CPU raises the underlying SEGV (AFAIK there's nobody to handle it though). \$\endgroup\$ – Joshua Nov 20 '16 at 17:18
26
\$\begingroup\$

Python 2, 13

exec'()'*7**6

Windows reports an error code of c00000fd (Stack Overflow) which I would assume is a subtype of segmentation fault.

Thanks to Alex A. and Mego, it is confirmed to cause segmentation faults on Mac and Linux systems as well. Python is the language of choice for portably crashing your programs.

\$\endgroup\$
  • 7
    \$\begingroup\$ Segmentation fault: 11 on Mac \$\endgroup\$ – Alex A. Nov 2 '15 at 1:29
  • 7
    \$\begingroup\$ Segmentation fault (core dumped) on Linux \$\endgroup\$ – Mego Nov 2 '15 at 1:30
  • \$\begingroup\$ Does this hang up first? \$\endgroup\$ – Mega Man Aug 13 '16 at 9:20
  • 1
    \$\begingroup\$ @MegaMan As in take a long time to finish? No, 7**6 is only about 100K so there's no perceptible delay. \$\endgroup\$ – feersum Aug 14 '16 at 2:46
  • \$\begingroup\$ Why does this work? It doesn't seem to on Python 3.6.8 on Mac OS. \$\endgroup\$ – Max Gasner Aug 5 at 17:28
22
\$\begingroup\$

pdfTeX (51)

\def~#1{\meaning}\write0{\expandafter~\string}\bye

This is actually probably a bug, but it is not present in the original TeX, written by Knuth: compiling the code with tex filename.tex instead of pdftex filename.tex does not produce a segfault.

\$\endgroup\$
21
\$\begingroup\$

LOLCODE, 4 bytes

OBTW

Does not work online, only in the C interpreter.

\$\endgroup\$
  • 24
    \$\begingroup\$ LOL FANCY CODE M8 8/8 KTHXBYE \$\endgroup\$ – Addison Crump Nov 2 '15 at 15:52
17
\$\begingroup\$

Python, 33 characters

>>> import ctypes;ctypes.string_at(0)
Segmentation fault

Source: http://bugs.python.org/issue1215#msg143236

Python, 60 characters

>>> import sys;sys.setrecursionlimit(1<<30);f=lambda f:f(f);f(f)
Segmentation fault

Source: http://svn.python.org/view/python/trunk/Lib/test/crashers/recursive_call.py?view=markup

This is the Python version I'm testing on:

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin

In general the Python interpreter is hard to crash, but the above is selective abusiveness...

\$\endgroup\$
16
\$\begingroup\$

Forth - 3 characters

0 @

(@ is a fetch)

\$\endgroup\$
  • 1
    \$\begingroup\$ Shortest one so far that will work on modern systems. \$\endgroup\$ – Demi Mar 6 '15 at 6:06
  • 2
    \$\begingroup\$ Which Forth? Gforth just says "Invalid memory address" \$\endgroup\$ – cat Mar 5 '16 at 1:25
15
\$\begingroup\$

C, 18

main(){raise(11);}
\$\endgroup\$
  • \$\begingroup\$ do you need to add #include <signal.h> in the code listing? \$\endgroup\$ – Florian Castellane Nov 28 '16 at 8:16
  • 5
    \$\begingroup\$ @FlorianCastellane: in C90 and lower, for any function call done without a visible declaration, the compiler implicitly declares it as int func(). i.e. a function returning int, taking unspecified parameters. In this case raise is a function returning int, taking an int argument, so this works out (even if the compiler complains). \$\endgroup\$ – Hasturkun Nov 28 '16 at 13:26
14
\$\begingroup\$

Perl ( < 5.14 ), 9 chars

/(?{??})/

In 5.14 the regex engine was made reentrant so that it could not be crashed in this way, but 5.12 and earlier will segfault if you try this.

\$\endgroup\$
  • \$\begingroup\$ I can reproduce this on Perl 5.14 (Debian) and 5.18 (Arch Linux). sprunge.us/RKHT \$\endgroup\$ – nyuszika7h Jan 21 '14 at 21:51
  • \$\begingroup\$ Reproduced with Perl v5.20.2 (windows) \$\endgroup\$ – mehi Mar 11 '16 at 13:38
14
\$\begingroup\$

W32 .com executable - 0 bytes

This will seem weird, but on 32 bit Windows systems, creating and executing an empty .com file may cause a segfault, depending on... something. DOS just accepts it (the 8086 having no memory management, there are no meaningful segments to fault), and 64 bit Windows refuses to run it (x86-64 having no v86 mode to run a .com file in).

\$\endgroup\$
13
\$\begingroup\$

brainfuck (2)

<.

Yes, this is implementation-dependent. SIGSEGV is the likely result from a good compiler.

\$\endgroup\$
  • 4
    \$\begingroup\$ How is a compiler that segfaults on that "good"? That < should either have no effect or wrap around. \$\endgroup\$ – nyuszika7h Jul 4 '14 at 17:38
  • 12
    \$\begingroup\$ Immediately producing a runtime error on bounds violation is best because it lets the programmer find and fix the bug as fast as possible. Letting the buggy program run for a while and corrupt memory haphazardly before crashing just makes the problem harder to diagnose. Preventing the crash entirely, as you suggest, is worst; the programmer may get the program "working" and then be publicly humiliated when it crashes on standard compilers and interpreters. \$\endgroup\$ – Daniel Cristofani Oct 12 '14 at 23:17
  • 1
    \$\begingroup\$ Conversely, catching bounds violations before runtime is not possible in general, nor especially useful in the cases where it is possible. Producing a more descriptive runtime error would be okay, but having the operating system catch it as a segfault is great because it doesn't have any speed cost. (In case it's not clear, the compiler itself doesn't segfault--it produces executables that segfault as soon as they try to access memory out of bounds.) \$\endgroup\$ – Daniel Cristofani Oct 12 '14 at 23:35
  • 4
    \$\begingroup\$ Can you provide an implementation that produces this behavior and was created before this challenge was posted? If not, this answer is invalid. \$\endgroup\$ – Mego Apr 25 '16 at 20:10
  • 1
    \$\begingroup\$ Bounds checks are implementation specific, so I'm sure there are some that would error on it. Would any SIGSEGV though? I doubt it. There are a large number of programs that depend on the array wrapping to the left though. It can be rather convenient having growable storage on both sides. \$\endgroup\$ – captncraig Dec 15 '16 at 20:01
12
\$\begingroup\$

Haskell, 31

foreign import ccall main::IO()

This produces a segfault when compiled with GHC and run. No extension flags are needed, as the Foreign Function Interface is in the Haskell 2010 standard.

\$\endgroup\$
10
\$\begingroup\$

C - 11(19) 7(15) 6(14) 1 chars, AT&T x86 assembler - 8(24) chars

C version is:

*(int*)0=0;

The whole program (not quite ISO-compliant, let's assume it's K&R C) is 19 chars long:

main(){*(int*)0=0;}

Assembler variant:

orl $0,0

The whole program is 24 chars long (just for evaluation, since it's not actually assembler):

main(){asm("orl $0,0");}

EDIT:

A couple of C variants. The first one uses zero-initialization of global pointer variable:

*p;main(){*p=0;}

The second one uses infinite recursion:

main(){main();}

The last variant is the shortest one - 7(15) characters.

EDIT 2:

Invented one more variant which is shorter than any of above - 6(14) chars. It assumes that literal strings are put into a read-only segment.

main(){*""=0;}

EDIT 3:

And my last try - 1 character long:

P

Just compile it like that:

cc -o segv -DP="main(){main();}" segv.c
\$\endgroup\$
  • 3
    \$\begingroup\$ in C isn't main; only 5 charecters \$\endgroup\$ – Arya Dec 26 '11 at 10:50
  • 1
    \$\begingroup\$ :Linker doesn't check whether main is function or not .It just pass it to the loader and return sigsegv \$\endgroup\$ – Arya Dec 26 '11 at 12:24
  • 1
    \$\begingroup\$ @FUZxxl In this case main is a zero-initialized global int variable, so what we get is a result of trying to execute some zero bytes. In x86 it'd be something like add %al,(%rax) which is a perfectly valid instruction which tries to reach memory at address stored in %rax. Chances of having a good address there are minimal. \$\endgroup\$ – Alexander Bakulin Dec 27 '11 at 20:35
  • 6
    \$\begingroup\$ Of course the last entry can be used for everything, you just have to supply the right compiler arguments. Which should make it the automatic winner of any code golf contest. :-) \$\endgroup\$ – celtschk Feb 4 '12 at 17:20
  • 5
    \$\begingroup\$ Usually compiler flags other than ones that choose the language version to use are counted towards the total. \$\endgroup\$ – Jerry Jeremiah Dec 11 '14 at 4:32
9
\$\begingroup\$

dc - 7 chars

[dx0]dx

causes a stack overflow

\$\endgroup\$
  • \$\begingroup\$ Is works, but can you elaborate? Why does it behave that way? \$\endgroup\$ – Stéphane Gourichon Nov 21 '16 at 12:17
  • 2
    \$\begingroup\$ [dx0] stores dx0 on the stack, then d duplicates the top stack element, then x pops the top stack element (dx0) and executes it. Which duplicates the top stack element, and starts executing it... the 0 needs to be there to prevent this being a tail call, so they all build up. \$\endgroup\$ – Ben Millwood Nov 26 '16 at 7:58
8
\$\begingroup\$

Perl, 10 / 12 chars

A slightly cheatish solution is to shave one char off Joey Adams' bash trick:

kill 11,$$

However, to get a real segfault in Perl, unpack p is the obvious solution:

unpack p,1x8

Technically, this isn't guaranteed to segfault, since the address 0x31313131 (or 0x3131313131313131 on 64-bit systems) just might point to valid address space by chance. But the odds are against it. Also, if perl is ever ported to platforms where pointers are longer than 64 bits, the x8 will need to be increased.

\$\endgroup\$
  • 1
    \$\begingroup\$ What is this 1x8 thing? \$\endgroup\$ – Hannes Karppila Dec 15 '16 at 10:19
  • \$\begingroup\$ @HannesKarppila It's a short way to write "11111111". \$\endgroup\$ – Ilmari Karonen Dec 15 '16 at 12:18
8
\$\begingroup\$

Python 33

import os
os.kill(os.getpid(),11)

Sending signal 11 (SIGSEGV) in python.

\$\endgroup\$
  • 2
    \$\begingroup\$ Also 33 characters: from os import* and kill(getpid(),11) \$\endgroup\$ – Timtech Jan 8 '14 at 15:45
8
\$\begingroup\$

OCaml, 13 bytes

Obj.magic 0 0

This uses the function Obj.magic, which unsafely coerces any two types. In this case, it coerces 0 (stored as the immediate value 1, due to the tag bit used by the GC) to a function type (stored as a pointer). Thus, it tries to dereference the address 1, and that will of course segfault.

\$\endgroup\$
  • 1
    \$\begingroup\$ it coerces 0 (stored as the immediate value 1) - why is 0 stored as 1? \$\endgroup\$ – Skyler Nov 3 '15 at 14:15
  • 1
    \$\begingroup\$ @Skyler see edit \$\endgroup\$ – Demi Nov 4 '15 at 19:02
  • 1
    \$\begingroup\$ Obj.magic()0 is one char shorter :) \$\endgroup\$ – Ben Millwood Nov 26 '16 at 7:53
8
\$\begingroup\$

Bash, 4 bytes

Golfed

. $0

Recursively include the script into itself.

Explained

Recursive "source" (.) operation causes a stack overflow eventually, and as Bash does not integrate with libsigsegv, this results in a SIGSEGV.

Note that this is not a bug, but an expected behavior, as discussed here.

Test

./bang 
Segmentation fault (core dumped)

Try It Online !

\$\endgroup\$
8
+200
\$\begingroup\$

Actually, 17 16 11 10 9 bytes

⌠[]+⌡9!*.

Try it online!

If the above doesn't crash, try increasing the number (multi-digit numbers are specified in Actually with a leading colon)

Crashes the interpreter by exploiting a bug in python involving deeply nested itertools.chain objects, which actually uses to implement the + operator.

\$\endgroup\$
7
\$\begingroup\$

C# - 62

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

Edit: 23

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

Must compile with /unsafe for this one to work. For some reason I don't understand, *(int*)0=0 just throws a NullReferenceException, while this version gives the proper access violation.

\$\endgroup\$
  • \$\begingroup\$ The int i=*(int*)0; returns a NullReferenceException for me. \$\endgroup\$ – Peter Olson Dec 30 '11 at 7:43
  • \$\begingroup\$ You can try to access a negative location, like *(int*)-1=0 and get an access violation. \$\endgroup\$ – Peter Olson Dec 30 '11 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 Jan 20 '12 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\$ – Konrad Borowski Sep 15 '18 at 20:55
7
\$\begingroup\$

PicoLisp - 4 characters

$ pil
: ('0)
Segmentation fault

This is intended behaviour. As described on their website:

If some programming languages claim to be the "Swiss Army Knife of Programming", then PicoLisp may well be called the "Scalpel of Programming": Sharp, accurate, small and lightweight, but also dangerous in the hand of the inexperienced.

\$\endgroup\$
7
\$\begingroup\$

F90 - 39 bytes

real,pointer::p(:)=>null()
p(1)=0.
end

Compilation:

gfortran segv.f90 -o segv 

Execution:

./segv 

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

Backtrace for this error:
#0  0x7FF85FCAE777
#1  0x7FF85FCAED7E
#2  0x7FF85F906D3F
#3  0x40068F in MAIN__ at segv.f90:?
Erreur de segmentation (core dumped)

Materials:

gfortran --version
GNU Fortran (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4
\$\endgroup\$
  • 1
    \$\begingroup\$ Nice first post. \$\endgroup\$ – Rɪᴋᴇʀ Mar 25 '16 at 18:03
6
\$\begingroup\$

19 characters in C

main(a){*(&a-1)=1;}

It corrupts return address value of main function, so it gets a SIGSEGV on return of main.

\$\endgroup\$
  • \$\begingroup\$ It depends on the stack frame layout, so in some architecture it can possibly not fail. \$\endgroup\$ – Alexander Bakulin Dec 27 '11 at 19:41
6
\$\begingroup\$

J (6)

memf 1

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

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

Cython, 14

This often comes in handy for debugging purposes.

a=(<int*>0)[0]
\$\endgroup\$
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\$

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\$
  • \$\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 Nov 28 '16 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 Nov 29 '16 at 16:13
5
\$\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\$
  • \$\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 Dec 16 '16 at 19:55
  • \$\begingroup\$ @tomsmeding this is window.clear, FF directly doesn't reveal it, it's a spidermonkey built-in \$\endgroup\$ – Downgoat Dec 16 '16 at 19:56
5
\$\begingroup\$

Pyth, 3 characters

j1Z

This would be the part where I explain how I came up with this answer, except I legitimately have no clue. If anyone could explain this for me, I'd be grateful.

Here it is in an online interpreter.

Explanation

j squares the base and calls itself recursively until the base is at least as large as the number. Since the base is 0, that never happens. With a sufficienly high recursion limit, you get a segfault.

- Dennis ♦

\$\endgroup\$
  • \$\begingroup\$ Figured something out! From browsing Pyth's source, I found that this code does j on 1 and 0, which tries to convert 1 into base 0. Why that segfaults, I have no idea... \$\endgroup\$ – NoOneIsHere Dec 23 '16 at 1:24
  • 1
    \$\begingroup\$ See here. j squares the base and calls itself recursively until the base is at least as large as the number. Since the base is 0, that never happens. With a sufficienly high recursion limit, you get a segfault. \$\endgroup\$ – Dennis Dec 23 '16 at 1:30
  • \$\begingroup\$ @Dennis IDEone \$\endgroup\$ – NoOneIsHere Dec 23 '16 at 1:35
  • \$\begingroup\$ @SeeRhino The Pyth interpreter sets the recursion limit to 100,000. At least on TIO, that's enough for a segfault. \$\endgroup\$ – Dennis Dec 23 '16 at 1:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.