Shortest code that raises a SIGSEGV

80

14

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

Arya

Posted 2011-12-26T08:36:13.680

Reputation: 991

32Wow. Possibly the shortest successful question. – Matthew Roh – 2017-02-09T11:42:53.317

Answers

116

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!

Konrad Borowski

Posted 2011-12-26T08:36:13.680

Reputation: 11 185

Default value may not be 0, and this may give a BUS error rather than a segmentation fault. – Macmade – 2013-08-10T08:25:32.473

5

@Macmade: Actually, it is 0. static variables start as 0, and main; is static, as I declared it outside function. http://c-faq.com/decl/initval.html

– Konrad Borowski – 2013-08-16T08:20:18.953

16last 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. – mniip – 2013-12-06T17:55:53.063

1main __attribute__((section(".text#")))=0xc3; FTFY (at least it seems to return without crashing on my x86). – jozxyqk – 2018-07-27T04:57:34.250

2@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 :). – Konrad Borowski – 2018-07-27T06:48:16.743

24Yep, segfaults in C are pretty much the default :P – Paul Draper – 2014-05-24T23:23:04.237

76

Bash, 11      

kill -11 $$

Joey Adams

Posted 2011-12-26T08:36:13.680

Reputation: 9 929

12@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 – HyperNeutrino – 2016-11-25T16:22:44.903

4@AlexL. other people seem to have spoiled that :( – theonlygusti – 2017-01-21T10:51:19.307

2@theonlygusti Yeah... That's too bad. :( Oh well, then I can upvote it now. – HyperNeutrino – 2017-01-21T14:27:17.440

46Signal 11 in 11 characters. Seems legit. – nyuszika7h – 2013-12-31T12:39:13.077

2Up to 42 upvotes, no touchee! – seadoggie01 – 2018-09-03T15:24:17.057

@JoeyAdams My shell script terminal just loaded for a long time, no segfault. – Sapphire_Brick – 2020-01-13T23:11:48.057

39

Assembly (Linux, x86-64), 1 byte

RET

This code segfaults.

Amol Sharma

Posted 2011-12-26T08:36:13.680

Reputation: 497

54@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. – celtschk – 2012-02-04T17:25:01.920

1@celtschk IIRC NTVDM will eke out on nonexistent addresses, and those not allocated to MS-DOS. – Reinstate Monica - ζ-- – 2013-01-31T01:32:38.710

2@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). – Joshua – 2016-11-20T17:18:19.473

1Whether ret by itself crashes depends on whether there's an outer environment to return to. For instance, if this is used as the body of main in a typical C environment, it will not crash (but it will exit with a garbage status), but if it's used as the sole contents of an ELF text segment, it typically will crash because the initial stack frame created by the OS has a null pointer for the return address. – zwol – 2016-11-20T22:59:45.390

1I have modified the answer to count bytes instead of characters. – qwr – 2018-04-07T19:18:00.970

7As an MSDOS .com file, it runs and terminates without error. – J B – 2011-12-26T19:10:37.467

see this code http://ideone.com/RMuLf

– Amol Sharma – 2011-12-26T19:46:21.513

10My point being: just specifying “assembly” isn't enough to make it segfault. – J B – 2011-12-26T19:56:22.637

'ret' by itself should be a valid program; I suspect that is an error in the emulator. – Sir_Lagsalot – 2012-01-20T16:19:13.797

26

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.

feersum

Posted 2011-12-26T08:36:13.680

Reputation: 29 566

7Segmentation fault: 11 on Mac – Alex A. – 2015-11-02T01:29:17.667

7Segmentation fault (core dumped) on Linux – Mego – 2015-11-02T01:30:58.707

Does this hang up first? – Mega Man – 2016-08-13T09:20:20.230

1@MegaMan As in take a long time to finish? No, 7**6 is only about 100K so there's no perceptible delay. – feersum – 2016-08-14T02:46:41.007

Why does this work? It doesn't seem to on Python 3.6.8 on Mac OS. – Max Gasner – 2019-08-05T17:28:29.953

@MaxGasner Try reading the programming language again :) – feersum – 2019-08-06T04:03:56.840

why does it work on py2? – Max Gasner – 2019-08-07T17:10:46.850

yes, obviously, but where? like is this a CPython implementation detail because the parser doesn't catch the syntax error early, etc. – Max Gasner – 2019-08-08T16:56:47.423

24

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.

Bruno Le Floch

Posted 2011-12-26T08:36:13.680

Reputation: 1 181

21

LOLCODE, 4 bytes

OBTW

Does not work online, only in the C interpreter.

a spaghetto

Posted 2011-12-26T08:36:13.680

Reputation: 10 647

24LOL FANCY CODE M8 8/8 KTHXBYE – Addison Crump – 2015-11-02T15:52:51.180

18

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

ChristopheD

Posted 2011-12-26T08:36:13.680

Reputation: 1 599

16

Forth - 3 characters

0 @

(@ is a fetch)

Troy Deck

Posted 2011-12-26T08:36:13.680

Reputation: 191

1Shortest one so far that will work on modern systems. – Demi – 2015-03-06T06:06:56.057

2Which Forth? Gforth just says "Invalid memory address" – cat – 2016-03-05T01:25:08.807

15

C, 18

main(){raise(11);}

Hasturkun

Posted 2011-12-26T08:36:13.680

Reputation: 1 206

do you need to add #include <signal.h> in the code listing? – Florian Castellane – 2016-11-28T08:16:23.623

5@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). – Hasturkun – 2016-11-28T13:26:21.207

14

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

Orion

Posted 2011-12-26T08:36:13.680

Reputation: 309

14

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.

whio

Posted 2011-12-26T08:36:13.680

Reputation: 141

Reproduced with Perl v5.20.2 (windows) – mehi – 2016-03-11T13:38:45.817

I can reproduce this on Perl 5.14 (Debian) and 5.18 (Arch Linux). http://sprunge.us/RKHT

– nyuszika7h – 2014-01-21T21:51:23.290

13

brainfuck (2)

<.

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

Daniel Cristofani

Posted 2011-12-26T08:36:13.680

Reputation: 947

5Can you provide an implementation that produces this behavior and was created before this challenge was posted? If not, this answer is invalid. – Mego – 2016-04-25T20:10:17.660

1Bounds 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. – captncraig – 2016-12-15T20:01:46.517

My compiler for Sun machines gave SIGSEGV, as of version 1.1 released in 2004. (http://web.archive.org/web/20040815081834/http://www.hevanet.com/cristofd/brainfuck/dbc.c) Because it was pretty obviously the best thing to do. (Any counterarguments?) I haven't done a survey of other people's brainfuck compilers that generate machine-language executables. If I bother I'll report back here afterward. (Because having array space available to the left is nonstandard, careful brainfuck programmers won't use that space deliberately. So it's helpful to let them know ASAP when they use it accidentally.)

– Daniel Cristofani – 2016-12-18T07:51:41.563

1Some brainfuck implementations let you go out into the wild west, and allocate tape memory (and do memory magicks) for you if you do so. So yes, it is implementation defined. – eaglgenes101 – 2017-11-04T02:31:30.693

Some do. Because many (if not most) do not, this "feature" is only used by those who don't care about making their programs portable or those who aren't thinking about it. For people who want to be careful, bounds checking is more useful. – Daniel Cristofani – 2017-11-06T09:58:10.740

4How is a compiler that segfaults on that "good"? That < should either have no effect or wrap around. – nyuszika7h – 2014-07-04T17:38:41.353

13Immediately 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. – Daniel Cristofani – 2014-10-12T23:17:37.613

1Conversely, 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.) – Daniel Cristofani – 2014-10-12T23:35:32.610

13

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.

Joey Adams

Posted 2011-12-26T08:36:13.680

Reputation: 9 929

10

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

Alexander Bakulin

Posted 2011-12-26T08:36:13.680

Reputation: 389

6Of 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. :-) – celtschk – 2012-02-04T17:20:36.097

4in C isn't main; only 5 charecters – Arya – 2011-12-26T10:50:09.153

@Arya: Huh? What do you mean? – Alexander Bakulin – 2011-12-26T11:01:40.790

only main;in file.c – Arya – 2011-12-26T12:18:57.887

1:Linker doesn't check whether main is function or not .It just pass it to the loader and return sigsegv – Arya – 2011-12-26T12:24:16.177

@Arya: Now I got it. Yep, your kung fu is better. – Alexander Bakulin – 2011-12-26T13:18:50.330

@Alexander---smart programmer – Arya – 2011-12-26T21:37:05.500

@Arya That may run fine (if it happens that the bytes at main appear to form valid instructions) or raise an SIGILL instead. – FUZxxl – 2011-12-26T22:23:40.003

1@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. – Alexander Bakulin – 2011-12-27T20:35:01.447

5Usually compiler flags other than ones that choose the language version to use are counted towards the total. – Jerry Jeremiah – 2014-12-11T04:32:05.470

9

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.

pppery

Posted 2011-12-26T08:36:13.680

Reputation: 3 987

9

dc - 7 chars

[dx0]dx

causes a stack overflow

Geoff Reedy

Posted 2011-12-26T08:36:13.680

Reputation: 2 828

Is works, but can you elaborate? Why does it behave that way? – Stéphane Gourichon – 2016-11-21T12:17:21.197

2[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. – Ben Millwood – 2016-11-26T07:58:08.317

8

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 !

zeppelin

Posted 2011-12-26T08:36:13.680

Reputation: 7 884

8

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.

Demi

Posted 2011-12-26T08:36:13.680

Reputation: 181

1it coerces 0 (stored as the immediate value 1) - why is 0 stored as 1? – Skyler – 2015-11-03T14:15:39.303

1@Skyler see edit – Demi – 2015-11-04T19:02:30.600

1Obj.magic()0 is one char shorter :) – Ben Millwood – 2016-11-26T07:53:11.167

8

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.

Ilmari Karonen

Posted 2011-12-26T08:36:13.680

Reputation: 19 513

1What is this 1x8 thing? – Hannes Karppila – 2016-12-15T10:19:49.767

@HannesKarppila It's a short way to write "11111111". – Ilmari Karonen – 2016-12-15T12:18:18.827

8

Python 33

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

Sending signal 11 (SIGSEGV) in python.

Daniel

Posted 2011-12-26T08:36:13.680

Reputation: 1 801

2Also 33 characters: from os import* and kill(getpid(),11) – Timtech – 2014-01-08T15:45:41.330

7

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.

Pierre Carrier

Posted 2011-12-26T08:36:13.680

Reputation: 191

7

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.

captncraig

Posted 2011-12-26T08:36:13.680

Reputation: 4 373

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. – Konrad Borowski – 2018-09-15T20:55:43.853

The int i=*(int*)0; returns a NullReferenceException for me. – Peter Olson – 2011-12-30T07:43:09.043

You can try to access a negative location, like *(int*)-1=0 and get an access violation. – Peter Olson – 2011-12-30T07:46:59.317

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. – captncraig – 2012-01-20T17:41:06.910

7

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

frozar

Posted 2011-12-26T08:36:13.680

Reputation: 71

1Nice first post. – Rɪᴋᴇʀ – 2016-03-25T18:03:07.977

6

J (6)

memf 1

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

marinus

Posted 2011-12-26T08:36:13.680

Reputation: 30 224

6

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.

saeedn

Posted 2011-12-26T08:36:13.680

Reputation: 1 241

It depends on the stack frame layout, so in some architecture it can possibly not fail. – Alexander Bakulin – 2011-12-27T19:41:33.983

6

Cython, 14

This often comes in handy for debugging purposes.

a=(<int*>0)[0]

boothby

Posted 2011-12-26T08:36:13.680

Reputation: 9 038

5

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)

Dennis Jaheruddin

Posted 2011-12-26T08:36:13.680

Reputation: 1 848

Please give Matlab version -- R2015B (and 2016B also) just throws an error: Error using setfield (line 56) At least one index is required. – Florian Castellane – 2016-11-28T08:24:03.713

@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. – Dennis Jaheruddin – 2016-11-29T16:13:12.767

5

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

Downgoat

Posted 2011-12-26T08:36:13.680

Reputation: 27 116

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? – tomsmeding – 2016-12-16T19:55:36.443

@tomsmeding this is window.clear, FF directly doesn't reveal it, it's a spidermonkey built-in – Downgoat – 2016-12-16T19:56:39.587

5

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 ♦

NO_BOOT_DEVICE

Posted 2011-12-26T08:36:13.680

Reputation: 51

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... – NoOneIsHere – 2016-12-23T01:24:37.087

1

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.

– Dennis – 2016-12-23T01:30:39.993

@Dennis IDEone

– NoOneIsHere – 2016-12-23T01:35:45.267

@SeeRhino The Pyth interpreter sets the recursion limit to 100,000. At least on TIO, that's enough for a segfault. – Dennis – 2016-12-23T01:38:33.490

5

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.

Random832

Posted 2011-12-26T08:36:13.680

Reputation: 796

4

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.

Charles Paulet

Posted 2011-12-26T08:36:13.680

Reputation: 51

3I'm pretty sure you have to score with the additional args – Blue – 2016-12-16T12:36:42.640

You have to add 14 bytes for the special flag. – Erik the Outgolfer – 2016-12-16T12:38:34.433

@ErikGolferエリックゴルファー -nostartfiles is actually 13 bytes long :) – Charles Paulet – 2016-12-16T13:34:06.380

1@CharlesPaulet I think you have to count the space too. – Erik the Outgolfer – 2016-12-16T13:37:59.780

3

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

Serverfrog

Posted 2011-12-26T08:36:13.680

Reputation: 245

It does the same as the Dyvil Answer below – Serverfrog – 2017-02-09T14:51:56.827

Ask the OP. After searching, I think Access Violation and SegFault are maybe two names for the same thing. – mbomb007 – 2017-02-09T14:58:39.337

TIO throws a SIGSEGV on OpenJDK, so I think its Possible that Oracle and OpenJDK throws same things but under different names. – Serverfrog – 2017-02-09T15:07:28.650

2Why the long names and import x.y.asdf; instead of import x.y.*; ? – MildlyMilquetoast – 2017-02-14T04:36:13.920

args -> a for a 3 byte savings – Poke – 2017-05-01T17:14:47.967

Remove the space before throws and the space before the declaration of c for a 2 byte savings – Poke – 2017-05-01T17:15:05.257

1Using java.lang.reflect.Constructor instead of importing it saves 9 bytes – Poke – 2017-05-01T17:16:26.950

Try it online! – Poke – 2017-05-01T17:17:46.423

This can be shortened by using var "keyword" introduced in Java 10 to avoid typing the long type name of getDeclaredConstructor result. – Konrad Borowski – 2018-03-30T18:34:37.787

3

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"))

ceilingcat

Posted 2011-12-26T08:36:13.680

Reputation: 5 503

Main is not loaded in at address 0. As such, that jmp alone is causing the segfault. (I'm pretty certain,at least) – moonheart08 – 2018-03-06T19:25:24.557

1@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 – ceilingcat – 2018-03-06T20:42:34.917

A long time later, i learned that the hard way (bugggssss!) Thanks. – moonheart08 – 2018-09-05T15:15:28.127

3

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.

Matceporial

Posted 2011-12-26T08:36:13.680

Reputation: 41

3

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.

Οurous

Posted 2011-12-26T08:36:13.680

Reputation: 7 916

1Nice, 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. – None – 2019-01-08T10:51:43.510

@Keelan I learn something new every time you comment :). I'll edit that in once I'm back at my computer. – Οurous – 2019-01-08T16:03:19.250

2

Perl 6, 22

shell "kill -11 $*PID"

Just shelling to whatever shell you have.

bb94

Posted 2011-12-26T08:36:13.680

Reputation: 1 831

Why not do it directly in bash (11 chars): kill -11 $$... – Elist – 2017-02-18T20:55:57.550

@Elist somebody already answered about bash – Sapphire_Brick – 2020-01-22T02:08:24.453

2

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

Clashsoft

Posted 2011-12-26T08:36:13.680

Reputation: 835

2

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

user62131

Posted 2011-12-26T08:36:13.680

Reputation:

2

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.

ceilingcat

Posted 2011-12-26T08:36:13.680

Reputation: 5 503

2

Ruby, 15 bytes

eval a='eval a'

Segfaults (Ruby 2.3 on Ubuntu xenial)

G B

Posted 2011-12-26T08:36:13.680

Reputation: 11 099

2

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.

James Holderness

Posted 2011-12-26T08:36:13.680

Reputation: 8 298

2

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

Johannes Kuhn

Posted 2011-12-26T08:36:13.680

Reputation: 7 122

2

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 ;).

Konrad Borowski

Posted 2011-12-26T08:36:13.680

Reputation: 11 185

Why is that arguably a bug? – Sapphire_Brick – 2020-02-14T21:18:16.427

2

x86 .COM, 2 Bytes

66 61 POPAD

x86 .COM, 5 3 Bytes

A3 FF FF

Write to the segment border

l4m2

Posted 2011-12-26T08:36:13.680

Reputation: 5 985

Does that work? I thought that DOS runs in real mode and has no memory protection whatsoever. – Konrad Borowski – 2018-04-07T19:01:15.670

@xfix in real mode segment limits are 0xFFFF – l4m2 – 2018-04-07T19:03:11.137

2

Haskell, 15 bytes

Causes a stackoverflow:

main=main>>main

Try it online!

ბიმო

Posted 2011-12-26T08:36:13.680

Reputation: 15 345

You can use m@main=m>>m – H.PWiz – 2018-09-02T00:08:14.620

1

Battlestar, 3 characters

ret

Test

 $ echo ret > main.bts
 $ bts main.bts
 (segfaults)

Alexander

Posted 2011-12-26T08:36:13.680

Reputation: 113

1

Whispers, 5 bytes

>> 1!

Try it online!

How it works

>> 1  - Call this line repeated
    ! - Prevent tail call

caird coinheringaahing

Posted 2011-12-26T08:36:13.680

Reputation: 13 702

1

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

Stan Strum

Posted 2011-12-26T08:36:13.680

Reputation: 436

actually, one of the other posts pointed out that main; works, and is shorter. – Sapphire_Brick – 2020-01-22T01:59:28.223

@Sapphire_Brick Welcome to Code Golf, where you will find answers posted not because they are the best, but because they are interesting. If there was to only have the shortest answers posted, then this place would be awful boring. – Stan Strum – 2020-01-22T05:03:22.990

The question itself says the shortest code. – Sapphire_Brick – 2020-02-14T21:13:18.460

@Sapphire_Brick Are you implying should another answer in the same language I used, I must remove my submission? No. I certainly will not do it myself, that is. Feel free to report this submission for moderator review. – Stan Strum – 2020-02-15T01:02:35.597

No, I don't care if your answer is in the same language, provided that there's no shorter answer already posted, but your answer was posted later and is longer than the other answer. – Sapphire_Brick – 2020-02-16T00:28:34.497

1

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.

user82200

Posted 2011-12-26T08:36:13.680

Reputation:

1

Nasm, 3 bytes.

Either

ret

or

nop

ret raises SIGSEGV via stack underflow, and nop raises SIGSEGV simply because there's no exit point.

Sapphire_Brick

Posted 2011-12-26T08:36:13.680

Reputation: 111

0

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.

Tau

Posted 2011-12-26T08:36:13.680

Reputation: 1 935

-1

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

FrenchKheldar

Posted 2011-12-26T08:36:13.680

Reputation: 115

2This 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. – None – 2017-02-14T15:08:34.463