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

4
\$\begingroup\$

C - 14 chars

Be sure to compile an empty file with cc -nostartfiles c.c

Explanation:

What went wrong is that we treated _start as if it were a C function, and tried to return from it. In reality, it's not a function at all. It's just a symbol in the object file which the linker uses to locate the program's entry point. When our program is invoked, it's invoked directly. If we were to look, we would see that the value on the top of the stack was the number 1, which is certainly very un-address-like. In fact, what is on the stack is our program's argc value. After this comes the elements of the argv array, including the terminating NULL element, followed by the elements of envp. And that's all. There is no return address on the stack.

\$\endgroup\$
  • 3
    \$\begingroup\$ I'm pretty sure you have to score with the additional args \$\endgroup\$ – Blue Dec 16 '16 at 12:36
  • \$\begingroup\$ You have to add 14 bytes for the special flag. \$\endgroup\$ – Erik the Outgolfer Dec 16 '16 at 12:38
  • \$\begingroup\$ @ErikGolferエリックゴルファー -nostartfiles is actually 13 bytes long :) \$\endgroup\$ – Charles Paulet Dec 16 '16 at 13:34
  • 1
    \$\begingroup\$ @CharlesPaulet I think you have to count the space too. \$\endgroup\$ – Erik the Outgolfer Dec 16 '16 at 13:37
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"))
\$\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

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

\$\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\$
  • 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 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 at 16:03
2
\$\begingroup\$

Perl 6, 22

shell "kill -11 $*PID"

Just shelling to whatever shell you have.

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

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

Ruby, 15 bytes

eval a='eval a'

Segfaults (Ruby 2.3 on Ubuntu xenial)

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

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

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

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

Haskell, 15 bytes

Causes a stackoverflow:

main=main>>main

Try it online!

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

Rust, 34 bytes

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

Just a null pointer assignment, nothing special here.


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

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

Main is usually a function ;).

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

x86 .COM, 2 Bytes

66 61 POPAD

x86 .COM, 5 3 Bytes

A3 FF FF

Write to the segment border

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

Battlestar, 3 characters

ret

Test

 $ echo ret > main.bts
 $ bts main.bts
 (segfaults)
\$\endgroup\$
1
\$\begingroup\$

Whispers, 5 bytes

>> 1!

Try it online!

How it works

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

C, 20 bytes

Not the shortest, but it occurred when I was programming and I thought it was mildy interesting. However, I do believe this error is different than the original error I occured (*** stack smashing detected ***), but this is a SIGBUS (10). I was going to post this to the SIGBUS question, but it says it has been closed as a duplicate of this </overexplanation>

f(){int*u;--u[-1];}

Basically decrements invalid points. Example output:

$ gcc -o program main.c && ./program
main.c:1:1: warning: type specifier missing, defaults to 'int'
      [-Wimplicit-int]
main(){int*u;--u[-1];}
^
1 warning generated.
Bus error: 10
$ echo $?
138
\$\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.

\$\endgroup\$
0
\$\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.

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

I too have a 1 byte solution (since you don't believe in 0 byte solution). I have my own programming (interpreted) language which seg faults on inputting character 's'.

Here is the interpreter code.

main() {
    char c;
    while(1) {
        scanf("%c", &c);
        if(c == 's')
            puts(0);
    }
}

To run it create a file myprogram.sig with some random string which contains 's' and follow below steps:

$ gcc compiler.c -o sigseglang  
$ ./sigseglang < myprogram.sig
Segmentation fault (core dumped)
\$\endgroup\$

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.