118
\$\begingroup\$

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

\$\endgroup\$
2
  • 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

85 Answers 85

6
\$\begingroup\$

Phooey, Interpreter Bug, 2 bytes

<?

Try it online!

This interpreter is so buggy it is beautiful. I can cause a bad free() with one byte of code in two ways. But that, unfortunately, is a SIGABRT. πŸ˜‚

A quick check of the source code will tell you that the interpreter does not support wrapping. However, the bug isn't "lul I read backwards and it crashes", it is a little more in depth.

The Phooey code translates to these function calls:

< tape.left(1) // move left one cell
? debug() // print debug info

So let's step through it:

First, we call tape.left(1).

    void left(int64_t amount) {
        right(-amount);
    }

This turns into tape.right(-1):

    void right(int64_t amount = -1) {
        pointer += -1;

Adding -1 to pointer results it being -1, since the initial value was zero.

However, let's double check what type pointer is:

    size_t pointer = 0;
    size_t furthest = 0;

pointer is a size_t, which is an unsigned type, meaning that this -1 turns into a REALLY big number. Specifically, SIZE_MAX, the largest object size C++ is allowed to handle.

        if(pointer > furthest)
            furthest = pointer;

We assign pointer to furthest, because SIZE_MAX > 0.

Now, we call debug():

void Phooey::debug() {
    std::cout << "Tape: " << tape << std::endl;
}

And this calls the operator overload function for std::ostream << Tape, and here is our bug:

std::ostream& operator<<(std::ostream& stream, Tape& tape) {
    for(size_t i = 0; i <= tape.furthest; i++) {
        stream << tape[i];
    }
}

Let's substitute tape.furthest, if the bug wasn't clear enough:

    for(size_t i = 0; i <= SIZE_MAX; i++) {
        stream << tape[i];
    }

This loop will keep reading data from the tape pointer and printing it, until it segfaults. It is actually an infinite loop otherwise: Since tape.furthest is SIZE_MAX, it will always be true, as SIZE_MAX + 1 == 0.

How ironic that the bug occurs in the debug() function.

A simple way to fix this would be to add wrapping support, making sure that the pointer is always in range. As a matter of fact, almost every bug in this program can be fixed with range checks.

Bonus!

debug() is the buggiest function in this program. It segfaults even without putting any ?s in your code!

<3-509

Try it online!

You may be saying, "How are you calling debug() without ??

And the answer is: ROP. πŸ˜‚

Specifically, on this exact build of Phooey, the tape is stored on the stack, and cells[-3] contains the return address from call Phooey::run(), 0x403957.

509 bytes before that is just after Phooey::debug() sets up its stack frame. (If I set the pointer to the start of the function, it crashes too early to be interesting since the stack is unaligned). That is why I subtract 509.

It segfaults because it is definitely NOT called how the code expects it to be, and rdi doesn't have the this pointer, so it crashes.

This is OBVIOUSLY going to be dependent on the system and binary itself.

\$\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\$

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"))
\$\endgroup\$
3
  • \$\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\$ Commented Mar 6, 2018 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
    Commented Mar 6, 2018 at 20:42
  • \$\begingroup\$ A long time later, i learned that the hard way (bugggssss!) Thanks. \$\endgroup\$ Commented Sep 5, 2018 at 15:15
5
\$\begingroup\$

Squire commit 93d3bf1, 6 bytes

" "*-1

A quite intriguing blunder.

My initial attempt was to allocateth \$\text{II}^\text{LXIV}-\text{I}\$ bytes of memory, but alas, Squire thwarteth me by limiting string lengths to \$\text{XXXII}\$-bit integers, and even my peasant computer with a mere \$\text{VIII}\$ gigabytes of RAM was impervious to said attacks, but lo! Even if malloc rewardeth null, Squire containeth a defense stronger than steel:

void *xmalloc(size_t length) {
        void *ptr = malloc(length);

        if (ptr == NULL) {
                fprintf(stderr, "error allocating %zu bytes of memory\n", length);
                // Alas, thwarted again with SIGABRT!
                abort();
        }

        return ptr;
}

Instead, I ventured into value.c and spied this:

        case SQ_TSTRING: {
                sq_number amnt = sq_value_to_number(rhs);

                struct sq_string *result = sq_string_alloc(AS_STRING(lhs)->length * amnt + 1);
                // ...
        }

As with most strings in C, Squire terminateth all strings with \N, so Sampersand addeth \$I\$ whilst calculating the length.

Intriguingly, \$\text{I} \times -{\text{I}} + \text{I} == \text{N}\$. Therefore, this rewardeth &sq_string_empty.

struct sq_string *sq_string_alloc(unsigned length) {
        if (length == 0)
                return &sq_string_empty;
        // ...
}

To be more swift, Squire containeth some "static" strings for common values like "false" or "".

struct sq_string {
        char *ptr;
        int refcount;
        unsigned length;
        bool borrowed;
};

struct sq_string sq_string_empty = {
    .ptr = "",
    .length = 0,
    .refcount = -1,
    .borrowed = false,
};

Curiously, we have a string literal treateth as char *, which, despite its mutable appearances, is actually a member of the evil .rodata clan. These sneaky impostors are indistinguishable from normal strings, unless one encanteth -Wwrite-strings.

Returning to value.c, the next line triggers the .rodata impostor:

                // Lo! Sampersand hath summoned nasal demons!
                *result->ptr = '\0';

In order to make thine computer repent from nasal demons, thy great and powerful Linux exorcises Squire with a SIGSEGV.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ I thoroughly enjoyed reading this \$\endgroup\$
    – Sampersand
    Commented Jun 17, 2021 at 2:05
5
\$\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\$
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\$
    – tomsmeding
    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\$
    – Downgoat
    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\$
    – Serverfrog
    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\$
    – mbomb007
    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\$
    – Serverfrog
    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\$
    – Poke
    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\$
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\$

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\$
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\$
    – user42682
    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\$
    – Οurous
    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;:?"~<}{zz165v3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O21LKJIB+))(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!

\$\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
+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\$
2
\$\begingroup\$

Perl 6, 22

shell "kill -11 $*PID"

Just shelling to whatever shell you have.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Why not do it directly in bash (11 chars): kill -11 $$... \$\endgroup\$
    – Elist
    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\$
    – H.PWiz
    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
2
\$\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.

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

x86 .COM, 2 Bytes

66 61 POPAD

x86 .COM, 5 3 Bytes

A3 FF FF

Write to the segment border

\$\endgroup\$
2
  • \$\begingroup\$ Does that work? I thought that DOS runs in real mode and has no memory protection whatsoever. \$\endgroup\$
    – null
    Commented Apr 7, 2018 at 19:01
  • \$\begingroup\$ @xfix in real mode segment limits are 0xFFFF \$\endgroup\$
    – l4m2
    Commented Apr 7, 2018 at 19:03
2
\$\begingroup\$

WebAssembly (WaWrapper), 12 bytes

(func $main)

Try it online!

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

x86 machine code - 1 byte

08048060 <_start>:
 8048060:       5c                       pop    esp

This is change value of address esp into value 0x1, and then raises a SIGSEGV.

(gdb) disassemble _start
Dump of assembler code for function _start:
   0x08048060 : pop    esp
End of assembler dump.
(gdb) b *0x08048060
Breakpoint 1 at 0x8048060
(gdb) r
Starting program: /home/user/programming/assembly/pop 

Breakpoint 1, 0x08048060 in _start ()
(gdb) i r $esp
esp            0xbfffed40   0xbfffed40
(gdb) c
Continuing.

Program received signal SIGSEGV, Segmentation fault.
0x08048061 in ?? ()
(gdb) i r $esp
esp            0x1      0x1
(gdb) 
\$\endgroup\$
2
\$\begingroup\$

Zig, 26 bytes

pub fn main()void{main();}
\$\endgroup\$

Your Answer

By clicking β€œPost Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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