Write the shortest code that raises a Segmentation Fault (SIGSEGV) in any programming language.
- 52\$\begingroup\$ Wow. Possibly the shortest successful question. \$\endgroup\$Matthew Roh– Matthew Roh2017-02-09 11:42:53 +00:00Commented 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\$rydwolf– rydwolf ♦2020-11-21 20:38:20 +00:00Commented Nov 21, 2020 at 20:38
- \$\begingroup\$ @MatthewRoh And yet the question could be golfed further. "Raise a SIGSEGV. Code golf." \$\endgroup\$Steve Bennett– Steve Bennett2025-05-20 00:24:39 +00:00Commented May 20 at 0:24
- \$\begingroup\$ @MatthewRoh I now have a new contender :) codegolf.stackexchange.com/questions/281871/output-your-user-id \$\endgroup\$Steve Bennett– Steve Bennett2025-05-22 23:41:04 +00:00Commented May 22 at 23:41
86 Answers
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.
- 5\$\begingroup\$ @Macmade: Actually, it is
0.staticvariables start as0, andmain;isstatic, as I declared it outside function. c-faq.com/decl/initval.html \$\endgroup\$null– null2013-08-16 08:20:18 +00:00Commented Aug 16, 2013 at 8:20 - 24\$\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
mainis 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.textand 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– mniip2013-12-06 17:55:53 +00:00Commented Dec 6, 2013 at 17:55 - 38\$\begingroup\$ Yep, segfaults in C are pretty much the default :P \$\endgroup\$Paul Draper– Paul Draper2014-05-24 23:23:04 +00:00Commented May 24, 2014 at 23:23
- 1\$\begingroup\$
main __attribute__((section(".text#")))=0xc3;FTFY (at least it seems to return without crashing on my x86). \$\endgroup\$jozxyqk– jozxyqk2018-07-27 04:57:34 +00:00Commented Jul 27, 2018 at 4:57 - 3\$\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\$null– null2018-07-27 06:48:16 +00:00Commented Jul 27, 2018 at 6:48
Bash, 11
kill -11 $$ - 70\$\begingroup\$ Signal 11 in 11 characters. Seems legit. \$\endgroup\$user344– user3442013-12-31 12:39:13 +00:00Commented Dec 31, 2013 at 12:39
- 19\$\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\$2016-11-25 16:22:44 +00:00Commented Nov 25, 2016 at 16:22
- 11\$\begingroup\$ @AlexL. other people seem to have spoiled that :( \$\endgroup\$user36219– user362192017-01-21 10:51:19 +00:00Commented Jan 21, 2017 at 10:51
- 5\$\begingroup\$ @theonlygusti Yeah... That's too bad. :( Oh well, then I can upvote it now. \$\endgroup\$2017-01-21 14:27:17 +00:00Commented Jan 21, 2017 at 14:27
- 3\$\begingroup\$ Up to 42 upvotes, no touchee! \$\endgroup\$seadoggie01– seadoggie012018-09-03 15:24:17 +00:00Commented Sep 3, 2018 at 15:24
Assembly (Linux, x86-64), 1 byte
RET This code segfaults.
- 8\$\begingroup\$ As an MSDOS .com file, it runs and terminates without error. \$\endgroup\$J B– J B2011-12-26 19:10:37 +00:00Commented Dec 26, 2011 at 19:10
- 13\$\begingroup\$ My point being: just specifying “assembly” isn't enough to make it segfault. \$\endgroup\$J B– J B2011-12-26 19:56:22 +00:00Commented Dec 26, 2011 at 19:56
- 65\$\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– celtschk2012-02-04 17:25:01 +00:00Commented Feb 4, 2012 at 17:25
- 2\$\begingroup\$ @celtschk IIRC NTVDM will eke out on nonexistent addresses, and those not allocated to MS-DOS. \$\endgroup\$nanofarad– nanofarad2013-01-31 01:32:38 +00:00Commented Jan 31, 2013 at 1:32
- 3\$\begingroup\$ Whether
retby itself crashes depends on whether there's an outer environment to return to. For instance, if this is used as the body ofmainin 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. \$\endgroup\$zwol– zwol2016-11-20 22:59:45 +00:00Commented Nov 20, 2016 at 22:59
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.
- 10\$\begingroup\$
Segmentation fault: 11on Mac \$\endgroup\$Alex A.– Alex A.2015-11-02 01:29:17 +00:00Commented Nov 2, 2015 at 1:29 - 10\$\begingroup\$
Segmentation fault (core dumped)on Linux \$\endgroup\$user45941– user459412015-11-02 01:30:58 +00:00Commented Nov 2, 2015 at 1:30 - 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– feersum2016-08-14 02:46:41 +00:00Commented Aug 14, 2016 at 2:46
- 5\$\begingroup\$ @MaxGasner Try reading the programming language again :) \$\endgroup\$feersum– feersum2019-08-06 04:03:56 +00:00Commented Aug 6, 2019 at 4:03
- 1\$\begingroup\$ Yeah, it doesn't work on 3.8.9 (or at least my build of 3.8.9) on OS X. -- at least this version is clever enough to instead give you a
RecursionError\$\endgroup\$Max Gasner– Max Gasner2021-06-23 18:40:01 +00:00Commented Jun 23, 2021 at 18:40
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.
LOLCODE, 4 bytes
OBTW Does not work online, only in the C interpreter.
- 34\$\begingroup\$ LOL FANCY CODE M8 8/8 KTHXBYE \$\endgroup\$Addison Crump– Addison Crump2015-11-02 15:52:51 +00:00Commented Nov 2, 2015 at 15:52
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).
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...
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) Forth - 3 characters
0 @ (@ is a fetch)
- 1\$\begingroup\$ Shortest one so far that will work on modern systems. \$\endgroup\$Demi– Demi2015-03-06 06:06:56 +00:00Commented Mar 6, 2015 at 6:06
- 2\$\begingroup\$ Which Forth? Gforth just says "Invalid memory address" \$\endgroup\$cat– cat2016-03-05 01:25:08 +00:00Commented Mar 5, 2016 at 1:25
- \$\begingroup\$ Works in pforth, for instance, but the 0 is unnecessary; the 1-byte program @ typically segfaults also, having fetched its address via stack underflow. \$\endgroup\$Yann Vernier– Yann Vernier2025-06-19 17:05:18 +00:00Commented Jun 19 at 17:05
brainfuck (2)
<. Yes, this is implementation-dependent. SIGSEGV is the likely result from a good compiler.
- 6\$\begingroup\$ How is a compiler that segfaults on that "good"? That
<should either have no effect or wrap around. \$\endgroup\$user344– user3442014-07-04 17:38:41 +00:00Commented Jul 4, 2014 at 17:38 - 24\$\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– Daniel Cristofani2014-10-12 23:17:37 +00:00Commented Oct 12, 2014 at 23:17
- 3\$\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– Daniel Cristofani2014-10-12 23:35:32 +00:00Commented Oct 12, 2014 at 23:35
- 6\$\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\$user45941– user459412016-04-25 20:10:17 +00:00Commented Apr 25, 2016 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– captncraig2016-12-15 20:01:46 +00:00Commented Dec 15, 2016 at 20:01
C, 18
main(){raise(11);} - 1\$\begingroup\$ do you need to add #include <signal.h> in the code listing? \$\endgroup\$Florian Castellane– Florian Castellane2016-11-28 08:16:23 +00:00Commented Nov 28, 2016 at 8:16
- 8\$\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 returningint, taking unspecified parameters. In this caseraiseis a function returning int, taking an int argument, so this works out (even if the compiler complains). \$\endgroup\$Hasturkun– Hasturkun2016-11-28 13:26:21 +00:00Commented Nov 28, 2016 at 13:26 - \$\begingroup\$ @Hasturkun
main(){main();}\$\endgroup\$Sapphire_Brick– Sapphire_Brick2020-03-09 01:16:50 +00:00Commented Mar 9, 2020 at 1:16
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.
- \$\begingroup\$ I can reproduce this on Perl 5.14 (Debian) and 5.18 (Arch Linux). sprunge.us/RKHT \$\endgroup\$user344– user3442014-01-21 21:51:23 +00:00Commented Jan 21, 2014 at 21:51
- 1\$\begingroup\$ Reproduced with Perl v5.20.2 (windows) \$\endgroup\$mihaipopescu– mihaipopescu2016-03-11 13:38:45 +00:00Commented Mar 11, 2016 at 13:38
- \$\begingroup\$ What about
/(?R)/on older Perl versions? \$\endgroup\$Sapphire_Brick– Sapphire_Brick2020-09-02 13:37:45 +00:00Commented Sep 2, 2020 at 13:37
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.
- \$\begingroup\$ Awwww. I was gonna post
import Foreign;main=peek nullPtr::IO Int, but that's 40. \$\endgroup\$Sapphire_Brick– Sapphire_Brick2020-12-25 20:02:29 +00:00Commented Dec 25, 2020 at 20:02
Python 33
import os os.kill(os.getpid(),11) Sending signal 11 (SIGSEGV) in python.
- 3\$\begingroup\$ Also 33 characters:
from os import*andkill(getpid(),11)\$\endgroup\$Timtech– Timtech2014-01-08 15:45:41 +00:00Commented Jan 8, 2014 at 15:45
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.
- 1\$\begingroup\$ What is this
1x8thing? \$\endgroup\$Hannes Karppila– Hannes Karppila2016-12-15 10:19:49 +00:00Commented Dec 15, 2016 at 10:19 - 1\$\begingroup\$ @HannesKarppila It's a short way to write
"11111111".\$\endgroup\$Ilmari Karonen– Ilmari Karonen2016-12-15 12:18:18 +00:00Commented Dec 15, 2016 at 12:18 - \$\begingroup\$ You can replace
1x8with$^, it's long enough in both 32 and 64 bit. \$\endgroup\$Sisyphus– Sisyphus2021-07-28 08:09:41 +00:00Commented Jul 28, 2021 at 8:09
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 - 1\$\begingroup\$ Nice first post. \$\endgroup\$Riker– Riker2016-03-25 18:03:07 +00:00Commented Mar 25, 2016 at 18:03
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 - 4\$\begingroup\$ in C isn't main; only 5 charecters \$\endgroup\$Anil Arya– Anil Arya2011-12-26 10:50:09 +00:00Commented Dec 26, 2011 at 10:50
- 3\$\begingroup\$ :Linker doesn't check whether main is function or not .It just pass it to the loader and return sigsegv \$\endgroup\$Anil Arya– Anil Arya2011-12-26 12:24:16 +00:00Commented Dec 26, 2011 at 12:24
- 1\$\begingroup\$ @FUZxxl In this case
mainis 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 likeadd %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– Alexander Bakulin2011-12-27 20:35:01 +00:00Commented Dec 27, 2011 at 20:35 - 9\$\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– celtschk2012-02-04 17:20:36 +00:00Commented Feb 4, 2012 at 17:20
- 7\$\begingroup\$ Usually compiler flags other than ones that choose the language version to use are counted towards the total. \$\endgroup\$Jerry Jeremiah– Jerry Jeremiah2014-12-11 04:32:05 +00:00Commented Dec 11, 2014 at 4:32
dc - 7 chars
[dx0]dx causes a stack overflow
- \$\begingroup\$ Is works, but can you elaborate? Why does it behave that way? \$\endgroup\$Stéphane Gourichon– Stéphane Gourichon2016-11-21 12:17:21 +00:00Commented Nov 21, 2016 at 12:17
- 4\$\begingroup\$
[dx0]storesdx0on the stack, thendduplicates the top stack element, thenxpops the top stack element (dx0) and executes it. Which duplicates the top stack element, and starts executing it... the0needs to be there to prevent this being a tail call, so they all build up. \$\endgroup\$Ben Millwood– Ben Millwood2016-11-26 07:58:08 +00:00Commented Nov 26, 2016 at 7:58 - \$\begingroup\$ @BenMillwood I wasn't sure if dc had TCO, so to find out that it definitely does is really cool. \$\endgroup\$Braden Best– Braden Best2024-05-30 23:22:10 +00:00Commented May 30, 2024 at 23:22
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
jsquares 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.
- \$\begingroup\$ Figured something out! From browsing Pyth's source, I found that this code does
jon1and0, which tries to convert1into base0. Why that segfaults, I have no idea... \$\endgroup\$NoOneIsHere– NoOneIsHere2016-12-23 01:24:37 +00:00Commented Dec 23, 2016 at 1:24 - 1\$\begingroup\$ See here.
jsquares 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– Dennis2016-12-23 01:30:39 +00:00Commented Dec 23, 2016 at 1:30 - \$\begingroup\$ @Dennis IDEone \$\endgroup\$NoOneIsHere– NoOneIsHere2016-12-23 01:35:45 +00:00Commented Dec 23, 2016 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– Dennis2016-12-23 01:38:33 +00:00Commented Dec 23, 2016 at 1:38
Actually, 17 16 11 10 9 bytes
⌠[]+⌡9!*. 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.
Python 3.8+, 47 bytes
eval((lambda:0).__code__.replace(co_consts=())) Not the shortest python entry by far, but this one works without any imports. And as a bonus, this bug is exploitable to get arbitrary code execution, if you're smart about it.
- \$\begingroup\$ Welcome to Code Golf, this is a pretty interesting answer! \$\endgroup\$2020-12-09 05:19:37 +00:00Commented Dec 9, 2020 at 5:19
- \$\begingroup\$ It's honestly amazing that this language that has such a simple interface when seen from above gives you such incredibly deep access into the language's own runtime internals. \$\endgroup\$AJMansfield– AJMansfield2021-01-29 16:14:30 +00:00Commented Jan 29, 2021 at 16:14
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.
- 3\$\begingroup\$ I thoroughly enjoyed reading this \$\endgroup\$Sampersand– Sampersand2021-06-17 02:05:36 +00:00Commented Jun 17, 2021 at 2:05
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.
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.
- 1\$\begingroup\$
it coerces 0 (stored as the immediate value 1)- why is 0 stored as 1? \$\endgroup\$Skyler– Skyler2015-11-03 14:15:39 +00:00Commented Nov 3, 2015 at 14:15 - 1\$\begingroup\$ @Skyler see edit \$\endgroup\$Demi– Demi2015-11-04 19:02:30 +00:00Commented Nov 4, 2015 at 19:02
- 1\$\begingroup\$
Obj.magic()0is one char shorter :) \$\endgroup\$Ben Millwood– Ben Millwood2016-11-26 07:53:11 +00:00Commented Nov 26, 2016 at 7:53
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.
- 3\$\begingroup\$ I'm pretty sure you have to score with the additional args \$\endgroup\$Blue– Blue2016-12-16 12:36:42 +00:00Commented Dec 16, 2016 at 12:36
- \$\begingroup\$ You have to add 14 bytes for the special flag. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2016-12-16 12:38:34 +00:00Commented Dec 16, 2016 at 12:38
- \$\begingroup\$ @ErikGolferエリックゴルファー -nostartfiles is actually 13 bytes long :) \$\endgroup\$Charles Paulet– Charles Paulet2016-12-16 13:34:06 +00:00Commented Dec 16, 2016 at 13:34
- 2\$\begingroup\$ @CharlesPaulet I think you have to count the space too. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2016-12-16 13:37:59 +00:00Commented Dec 16, 2016 at 13:37
Phooey, Interpreter Bug, 2 bytes
<? 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 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.
Python, 53 characters
class A:__lt__=lambda s,o:o.clear()or s vars(A)>A()<0 This is a bit longer than some other solutions, but unlike some other solutions it
- works in modern python versions (tested in 3.7.17, 3.8.17, 3.9.17, 3.10.12, 3.11.8 and 3.12.2)
- doesn't look like it does anything dangerous/suspicious/illegal at first glance
- showcases an actual interpreter crash rather than just explicitly dereferencing null/execing invalid code/etc
Btw, don't report this upstream, this issue is already known and closed as "wontfix" in CPython: https://github.com/python/cpython/issues/88004
Explanation:
The important part is essentially
class A: def __lt__(self, other): other.clear() AnyClass.__dict__ > A() AnyClass can be any class (A in the short version) and vars(A) is a shorthand for A.__dict__.
The issue here is that the class __dict__ property is supposed to be of type mappingproxy that is implemented as thin wrapper around regular dicts. This special type is supposed to make this dictionary immutable/read-only:
AnyClass.__dict__["foo"] = 0 # TypeError: 'mappingproxy' object does not support item assignment del AnyClass.__dict__["foo"] # TypeError: 'mappingproxy' object does not support item deletion AnyClass.__dict__.clear() # AttributeError: 'mappingproxy' object has no attribute 'clear' However, it's possible to circumvent this protection using python's data model. Specifically, mappingproxy doesn't reimplement all of the required methods itself, but instead just delegates to the underlying dict implementation.
So, when we do AnyClass.__dict__ > A() the following happens:
m = AnyClass.__dict__is of typemappingproxya = A()is of typeAwe try to execute
m > aorm.__gt__(a)mappingproxydoesn't implement__gt__, so it delegates this call todictthis essentially does something similar to
# except this isn't a real property so it isn't accessible from pure python d = m.__internal_reference_to_underlying_dict return d.__gt__(a)where
dis the actual underlying storage of typedict, not the safe/immutable/read-onlymappingproxywrapperwe try to execute
d.__gt__(a)dictdoes implement__gt__, but it doesn't know what to do with our custom typeA, so it returns the specialNotImplementedvaluepython's data model says that when
x.__gt__(y)(x > y) returnsNotImplemented, you should try the swapped versiony.__lt__(x)(y < x) before failingwe try to execute
a.__lt__(d)our custom class
Adoes have an implementation for__lt__that callsclear()on the "other" object, in this case -d
So with this, we were able to call clear() on the underlying storage for the class __dict__ that was supposed to be made immutable by exposing it through a mappingproxy. This breaks some core assumptions that python heavily relies on. After that, it's pretty easy to cause a SEGFAULT by attempting to interact with an instance of AnyClass (or A in the minified version).
The use of __lt__ and > here is not mandatory, this also works with any other paired binary operator (eq/ne, add/radd, sub/rsub, mul/rmul, etc).
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 it online!, 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")) - \$\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– moonheart082018-03-06 19:25:24 +00:00Commented Mar 6, 2018 at 19:25
- 2\$\begingroup\$ @moonheart08 it isn't jumping to absolute address
0, it's jumping to thepush %eax. Jumping to absolute address0would require something likexor %eax, %eax; jmp *%eax\$\endgroup\$ceilingcat– ceilingcat2018-03-06 20:42:34 +00:00Commented Mar 6, 2018 at 20:42 - \$\begingroup\$ A long time later, i learned that the hard way (bugggssss!) Thanks. \$\endgroup\$moonheart08– moonheart082018-09-05 15:15:28 +00:00Commented Sep 5, 2018 at 15:15
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.
- 1\$\begingroup\$ It depends on the stack frame layout, so in some architecture it can possibly not fail. \$\endgroup\$Alexander Bakulin– Alexander Bakulin2011-12-27 19:41:33 +00:00Commented Dec 27, 2011 at 19:41
- \$\begingroup\$ Why not simply
main;, ormain(){*""=0;}? \$\endgroup\$Sapphire_Brick– Sapphire_Brick2020-11-16 01:23:49 +00:00Commented Nov 16, 2020 at 1:23 - \$\begingroup\$ @Sapphire_Brick
main;is already given in another answer. \$\endgroup\$saeedn– saeedn2020-11-17 04:08:51 +00:00Commented Nov 17, 2020 at 4:08 - \$\begingroup\$ @saeedn Then why post it at all? This one isn't even the second to shortest! \$\endgroup\$Sapphire_Brick– Sapphire_Brick2020-11-17 05:27:59 +00:00Commented Nov 17, 2020 at 5:27
- \$\begingroup\$ @Sapphire_Brick At the time I was posting mine,
main;wasn't posted and I didn't know it works. I was only pointing out that it is already given and no point in changing my answer. Furthermore, people here don't just post only for the shortest, sometimes a different way of solving the problem is also interesting. \$\endgroup\$saeedn– saeedn2020-11-18 17:20:38 +00:00Commented Nov 18, 2020 at 17:20