86
\$\begingroup\$

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

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

58 Answers 58

1
2
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

| improve this answer | |
\$\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
3
\$\begingroup\$

Ruby, 15 bytes

eval a='eval a'

Segfaults (Ruby 2.3 on Ubuntu xenial)

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

x86 and x86_64 machine language, 3 bytes

0:       50                      push   %eax
1:       eb fd                   jmp    0

This pushes the value of the EAX (or RAX in long mode) register to the stack in a loop until the stack overflows.

To try this, compile and run the following C program.

const char main[]="\x50\xeb\xfd";

To try it on Windows, prepend the following to mark main as executable.

#pragma section("foo", execute)
__declspec(allocate("foo"))
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Main is not loaded in at address 0. As such, that jmp alone is causing the segfault. (I'm pretty certain,at least) \$\endgroup\$ – moonheart08 Mar 6 '18 at 19:25
  • 1
    \$\begingroup\$ @moonheart08 it isn't jumping to absolute address 0, it's jumping to the push %eax. Jumping to absolute address 0 would require something like xor %eax, %eax; jmp *%eax \$\endgroup\$ – ceilingcat Mar 6 '18 at 20:42
  • \$\begingroup\$ A long time later, i learned that the hard way (bugggssss!) Thanks. \$\endgroup\$ – moonheart08 Sep 5 '18 at 15:15
3
\$\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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It does the same as the Dyvil Answer below \$\endgroup\$ – Serverfrog Feb 9 '17 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 Feb 9 '17 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 Feb 9 '17 at 15:07
  • 2
    \$\begingroup\$ Why the long names and import x.y.asdf; instead of import x.y.*; ? \$\endgroup\$ – MildlyMilquetoast Feb 14 '17 at 4:36
  • 1
    \$\begingroup\$ Using java.lang.reflect.Constructor instead of importing it saves 9 bytes \$\endgroup\$ – Poke May 1 '17 at 17:16
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.

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
  • 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\$ – user42682 Jan 8 '19 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 Jan 8 '19 at 16:03
3
\$\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 ;).

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Perl 6, 22

shell "kill -11 $*PID"

Just shelling to whatever shell you have.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Why not do it directly in bash (11 chars): kill -11 $$... \$\endgroup\$ – Elist Feb 18 '17 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
| improve this answer | |
\$\endgroup\$
2
+100
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
2
\$\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.)

| improve this answer | |
\$\endgroup\$
2
\$\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.

| improve this answer | |
\$\endgroup\$
2
\$\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

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Haskell, 15 bytes

Causes a stackoverflow:

main=main>>main

Try it online!

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You can use m@main=m>>m \$\endgroup\$ – H.PWiz Sep 2 '18 at 0:08
2
\$\begingroup\$

x86 .COM, 2 Bytes

66 61 POPAD

x86 .COM, 5 3 Bytes

A3 FF FF

Write to the segment border

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Does that work? I thought that DOS runs in real mode and has no memory protection whatsoever. \$\endgroup\$ – Konrad Borowski Apr 7 '18 at 19:01
  • \$\begingroup\$ @xfix in real mode segment limits are 0xFFFF \$\endgroup\$ – l4m2 Apr 7 '18 at 19:03
2
\$\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 raises SIGSEGV via stack underflow. All the other opcodes raise SIGSEGV simply because there's no exit point.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Battlestar, 3 characters

ret

Test

 $ echo ret > main.bts
 $ bts main.bts
 (segfaults)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Whispers, 5 bytes

>> 1!

Try it online!

How it works

>> 1  - Call this line repeated
    ! - Prevent tail call
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Common Lisp (SBCL), 79 bytes.

SBCL captures pretty much every exception and signal, but we can cause an "Unhandled memory exception" which is the result of a SIGSEGV. We must tell SBCL to not consider type safety and just add a fixnum to a float, which ends up disastrous.

(defun f(x)(declare (optimize (safety 0))(fixnum x))(the fixnum (1+ x)))(f 0.0)

My SBCL image errors with:

Unhandled memory fault at #x14.
   [Condition of type SB-SYS:MEMORY-FAULT-ERROR]

Evaluating (f '(1 5)) returned a garbage object, then (gc) threw Lisp into the low-level debugger after it tried to GC that object presumably. I don't see the difference in results since it is possible to jump back into Lisp from this state, and I imagine this is 100% platform dependent behavior.

| improve this answer | |
\$\endgroup\$
1
\$\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;:?"~<}{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:877LQPO21LKJIB+))(CBA@?8=~;:{87w5vt2sq/pn,+l)i!~%fd"!b}_uty\ZYYnsrUpRhglOMiLJfIGcFD`_^A@[ZYXWPU8SRQ4ONM//DIH+)E>=B%#?"~<}{9zx6wutt+0/pn,%$)jhgg|#"ca}vuz][ZZotsVTpihmPNMMbgfIGc\[`CA@@UZY<:VONSRQ4I2MLKJIH+dv'Ps$_"]~[|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!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

x86 assembly (intel syntax), 12 chars

lgdt [0x123]

How it works

You force the cpu to load a GDT table at a random address(0x123 in this case) , and of course it'll segfault. And if that location is actually a valid gdt, you should still trigger a GPF. Also, this might triple fault if you use it on msdos.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Io, 25 bytes

Recursively executing the current file raises a segmentation fault. (You know, the system running Io obviously doesn't implement tail-call optimization.)

doFile(System args at(0))

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

C++, 19 bytes.

int main(){main();}

Not very interesting, just stack overflow. (pun not intended)

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Swift 5, 29 characters:

func x(){y()}
let y={x()}
x()
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Go, 29 characters

package x;func x(y*int){*y=4}
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

WebAssembly (WaWrapper), 12 bytes

(func $main)

Try it online!

| improve this answer | |
\$\endgroup\$
-1
\$\begingroup\$

F90 - 25 chars

REAL A(1)
n=2
A(n)=0
END

Compiled with Intel compiler 12.0 which actually refuses to compile without the intermediate n as it detects the bound error. Does this count as a segfault?:

ifort -C sigsegv.F90 
./a.out 
forrtl: severe (408): fort: (2): Subscript #1 of the array A has value 2 which is greater than the upper bound of 1
| improve this answer | |
\$\endgroup\$
  • 3
    \$\begingroup\$ This isn't a segmentation fault unless it actually causes an OS-defined signal representing an access violation or similar. That error message looks like it was printed by the implementation, meaning that this answer is invalid. \$\endgroup\$ – user62131 Feb 14 '17 at 15:08
-1
\$\begingroup\$

TI-BASIC, 5 bytes

Archive A:A

Archives the variable A and then tries to get the value of A.
Throws the ERR:ARCHIVED error when used.

This is the closest thing you'd get to a segmentation fault in TI-BASIC, since archived data cannot be accessed directly.

In other words, the software has attempted to access a restricted area of memory.


Note: TI-BASIC is a tokenized language. Character count does not equal byte count.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It's not a segmentation fault. \$\endgroup\$ – Sapphire_Brick Jun 11 at 14:45
  • \$\begingroup\$ @Sapphire_Brick It most definitely is. "A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system)." (source) Archived data can't be accessed in TI-BASIC, simple as that. Do your research before commenting next time. \$\endgroup\$ – Tau Jun 17 at 0:53
  • \$\begingroup\$ You seem to be saying "Fish can swim; I can swim, so I am a fish.". A segmentation fault is more specific than the definition you gave. It has to be the signal SIGSEGV, not just any memory permission error. Suppose you try to use a bash command that you don't have permission to use. Is that a segmentation fault? Of course not. \$\endgroup\$ – Sapphire_Brick Jun 17 at 1:06
  • \$\begingroup\$ Fair enough. Though, you could've explained that in a way without trying to use a strawman like "Fish can swim; I can swim, so I am a fish." \$\endgroup\$ – Tau Jun 17 at 3:13
1
2

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.