Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Write a perfectly legal code in a decent language of your choice whose compiling will either crash the compiler or send it into an infinite loop (infinite compile time).

Restrictions:

  • Use a standard language that is used in real world.
  • Use a standard, well-developed compiler (no answers like "I wrote my C compiler that crashes on everything").
  • The code must be legal in the language (so most likely you'll have to exploit a compiler or a language bug).
  • Give your compiler version and options used so that others can replicate it.
  • Explain why the compiler crashed, if possible.

Have fun :)

share|improve this question
4  
Could you elaborate on what you mean by "crash"? – Mr. Llama Sep 6 '12 at 19:45
    
@GigaWatt I mean that the compiler stops in an uninteded way. Neither by successfully compiling the input nor by issuing an error message. It has to really crash, like segfault, eating up all the memory, throwing an unchecked exception etc. – Petr Pudlák Sep 6 '12 at 19:50
    
wiki.python.org/moin/CrashingPython – SeanC Sep 7 '12 at 20:46
1  
This contest is mostly just an exercise in searching bug reports for test cases :/ – Sparr Oct 14 '15 at 18:28
    
Is crashing an interpreter permitted? – Mark Oct 17 '15 at 3:17

26 Answers 26

up vote 20 down vote accepted

I'm pretty sure it's been fixed now, but it used to be that you could crash the Java compiler (or, crash Eclipse) by writing

class Foo {
  static double d = 2.2250738585072012e-308;
}

http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/

Actually, according to that page, the compiler will just hang, not crash. Still, I thought that was pretty fun.

share|improve this answer

My favorite solution for GHC:

data Bad a = C (Bad a -> a)

xx :: Bad a -> a
xx (x@(C x')) = x' x

omega :: a
omega = xx (C xx)

main = omega

For GHC 6.12.1 both ghci Bad.hs and ghc Bad.hs loop infinitely. GHC 7.4.1 loops infinitely when ghc -O2 Bad.hs is executed.

Explanation: omega is defined using an infinite recursion (the only way it can inhabit any type). Compiler's inliner sees xx as a simple, non-recursive function, so it tries to inline it in the definition of omega. It results in (\x@(C x') -> x' x) (C xx). Seeing a pattern match on a constructor the compiler tries to reduce it, getting xx (C xx) again and loops. The trick is that xx is actually recursive, but the recursion is hidden within the data type.

Note: While writing the puzzle, I forgot I left GHC running in the infinite loop. It took all my memory, crashed Firefox and I barely managed to kill it without hard reset.

share|improve this answer
4  
+1 just for the trouble you went through for the answer :P – UnkwnTech Sep 6 '12 at 21:13
4  
@UnkwnTech :-) Actually I discovered this by an accident when trying to implement recursion using a recursive data type only. – Petr Pudlák Sep 6 '12 at 21:17

This is easy in any dependently-typed language. Type-checking general dependent types is undecidable since it may require arbitrarily complex computations (Turing-complete). You can simply encode in a dependent type a too-large value. Then the type-checker will use all available memory and crash. For instance, in Coq, ReyCharles gives the example of Compute 70000., which causes the type-checker to construct a giant Peano numeral and crash.

In more common languages that support some sort of macro expansion or metaprogramming, you can do something similar. For example, you can use all available memory in C:

#include <stdio.h>
#define a printf("%s", "Hello, world!\n");
#define b a a a a a a a a a a a a a a a a
#define c b b b b b b b b b b b b b b b b
#define d c c c c c c c c c c c c c c c c
#define e d d d d d d d d d d d d d d d d
#define f e e e e e e e e e e e e e e e e
// ...
#define z y y y y y y y y y y y y y y y y
int main() { z }

The D programming language allows compile-time function execution. This can be used to compute something at compile time that is too large to fit in memory. Something similar can be achieved using C++ template metaprogramming.

In XML (not a compiled programming language, but an XML processor is analogous to a compiler), expanding entities can make the processor run out of memory:

<?xml version="1.0"?>
<!DOCTYPE lolz [
 <!ENTITY lol "lol">
 <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
 <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
 <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
...
]>
<lolz>&lol999;</lolz>

This is called the billion laughs attack.

share|improve this answer
3  
+1 for the "billion laughs attack" - what a name – Bojangles Apr 21 '13 at 6:57
2  
Note that <lolz>&lol999;</lolz> is 10^999 laughs, not a billion. The linked references uses <lolz>&lol9;</lolz>, which is actually a billion. – mbomb007 Oct 14 '15 at 14:27

C#

Found this on a stackoverflow question:

using System;
using System.Linq;

public class Test
{
    public static void Main()
    {
        Enumerable.Range(0, 1).Sum(a =>
        Enumerable.Range(0, 1).Sum(b =>
        Enumerable.Range(0, 1).Sum(c =>
        Enumerable.Range(0, 1).Sum(d =>
        Enumerable.Range(0, 1).Sum(e =>
        Enumerable.Range(0, 1).Sum(f =>
        Enumerable.Range(0, 1).Count(g => true)))))));
    }
}

The compiler eventually will crash.

The issue seems related to type inference and/or lambda generation combined with overload resolution.

share|improve this answer
8  
+1 for making Visual Studio's intellisense consume all available memory and crash the IDE. This is a prank I shall use only for the power of good. – Mark Oct 14 '15 at 14:18

how about if you can crash the IDE by typing in code?

in any Microsoft Office application, try this:

ALT+F11 to get to the VBA window, then try the following code

sub foo()
dim v(1 to 3, 1 to 3)
redim preserve v(,1 to 5)

and behold:

Excel Death

You can simply type redim preserve v(,1 to 5) into the immediate window, and it will crash after you press ENTER !

share|improve this answer
    
nice, but more like "crash your favourite interpreter" – mbx Sep 7 '12 at 20:16
    
Could I get a quick rundown on why this works? – Mr. Llama Jan 7 '13 at 16:23
1  
@GigaWatt, it's discussed in a little more depth here, but it appears that the IDE cannot cope with errors (unexpected symbol , and expected ,) – SeanC Jan 7 '13 at 20:28

Perl (15)

BEGIN{1while 1}

This creates an infinite loop at compile time:

A BEGIN code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed.

(from perlmod)

And that's why Perl isn't able to complete parsing the code. This doesn't terminate:

$ perl -MO=Deparse -e 'BEGIN{1while 1}'
share|improve this answer

J

This segfaults the J interpreter (at least on Linux):

15!:1[3#2

It tries to read from memory address 2. Interestingly, if you try it with 0 or 1, you get domain error.

share|improve this answer

TeX

\def\x{\x}\x

TeX is a macro-expansion language. Here we define the expansion of the macro \x to be \x again, and then we add afterwards an invocation of \x. TeX gets stuck endlessly replacing \x with \x.

share|improve this answer
1  
Note: this isn't the shortest way to achieve this. TeX has a notion of "active characters", which essentially are characters that are treated as macro names. So you can shave off 3 characters from this. – Hammerite May 7 '14 at 7:54

Common Lisp

Macros make it easy:

(defmacro loop-forever ()
  (loop for x from 0 collecting x))

(defun compile-me ()
  (loop-forever))

Compiling compile-me calls loop-forever, which exhausts heap memory during its expansion and crashes the compiler. If you just want to make the compiler hang indefinitely, then this definition of loop-forever will do it:

(defmacro loop-forever ()
  (loop))

This should work using any CL implementation, unless yours is extremely clever and can detect simple infinite loops, but I seriously doubt any do this. Full protection against this is impossible, of course.

share|improve this answer
    
meh. Lisp makes writing compile-time infinite loops too easy. Now if you had actually crashed the compiler... – Jan Dvorak May 3 '14 at 15:57
    
@JanDvorak The only way to crash a Lisp is to call a C library through FFI ;-) – coredump Oct 14 '15 at 19:24
    
@coredump Please do. At compile time :-) – Jan Dvorak Oct 14 '15 at 20:23
    
(defmacro loop-forever () (loop)) (defun compile-me () (loop-forever)) should be sufficient. It hangs CCL for me. – nanny Oct 15 '15 at 13:27

Smalltalk (Squeak dialect, version 4.x)

Very easy, just evaluate this, or accept a method with this literal

1.0e99999999999999999999

It will try to evaluate the power of 10 in Large Integer arithmetic, just for correctly rounding inf Tsss ;)

share|improve this answer
    
Do you need more than four 9s? – Joe Z. May 3 '14 at 17:57

PHP 5.3.1 (Segfaults interpreter) (Bug 50261, fixed in 5.3.3)

   class testClass
   {
       function testClass ()
       {
           echo 'Output string!';
       }
   }

   class testClass2 extends testClass
   {
       function __construct ()
       {
           call_user_func(array('parent', '__construct'));
       }
   }

   new testClass2;

This one was a bit of a problem, because the code above was common in a lot of the code I was working with, making this a fairly widespread issue for us.

(If I recall correctly, at one point this was the only way to call parent constructors in PHP.)

share|improve this answer

D

(DMD32 D Compiler v2.067.1, Windows build)

enum x = "mixin(x);";
mixin(x);

Note that this will send the compiler into an infinite loop and crash it.

Error: out of memory

Mechanical snail suggested that compile-time programming features in D could be abused for this purpose, but the solution is perhaps simpler than the kind of techniques he had in mind.


For those who aren't familiar with 'string mixins', it's a fairly straightforward macro feature. When the compiler encounters mixin("asdf"), it substitutes it with the contents of the string, asdf, and tries to compile it again.

The solution above will be expanded like:

mixin(x);  ->  mixin("mixin(x);");  ->  mixin(x);

So unless the compiler tries to detect this expand-to-same case, it'll enter an infinite loop of expansion.

share|improve this answer

Perl

This defines operator overloading at compile time, and runs code at compile time which adds the instances of class together.

(by the way, normally infinite recursion would eat all the memory, but with overloading, it just crashes)

package MyAmazingClass;
use 5.010;

use overload '+' => sub {
    my ($first, $second) = @_;
    return $first + $second;
};

sub new {
    my $self = shift;
    return bless {}, $self;
}

# BEGIN runs code at compile time
BEGIN {
    my $instance = MyAmazingClass->new;
    my $sum = $instance + $instance;
    say $sum;
}

Output:

fish: Job 1, 'perl' terminated by signal SIGSEGV (Address boundary error)
share|improve this answer

Scheme

(define-syntax s
    (syntax-rules ()
        ((_ (t) ...) (s (t t) ... (t t) ...))
        ((_ (t u) ...) (s (t) ... (u) ...))))
(s (+))

My compiler, Chicken, made the mistake of attempting to expand macros at compile time for "run-time performance" or something. So it payed the price of expanding this one. I've read R5RS. No one said macros had to be expanded at compile time.

Essentially what's going on is the macro expands to an expression of infinite size, constantly doubling in size. Well, to be technical, doubling every other expansion. The compiler's fate is sealed. At least on my system, Chicken caps at 2GB, stalls for a long time trying to garbage collect, then crashes after the garbage collector gives up. It does take a while though because of all the computationally expensive hygienic magic occurring.

Switching between expressions of the form

(s (+) (+) (+) (+) ....

and

(s (+ +) (+ +) (+ +) (+ +) ....

seems to very, very dramatically increase the rate of memory consumption as compared to:

(define-syntax s
    (syntax-rules ()
        ((_ t ...) (s t ... t ...))))
(s +)

I suspect Chicken is a pretty hardy compiler that has some ways of avoiding deep analysis of syntactic expressions when it can get away with it, but my final solution forces the pattern matcher to really dive in.

share|improve this answer
    
Woah. +1, and welcome to Programming Puzzles and Code Golf Stack Exchange. If you need any help, or just want to talk, feel free to reply to this comment with @wizzwizz4. – wizzwizz4 Mar 27 at 8:34

This is my original and concise method to crash GolfScript:

{1.}do

What this does is set up a forever loop that keeps on pushing 1 onto the stack until memory runs out.

In C/C++, I believe that this original piece of code would crash the compiler:

#define a bb
#define b aa
int main(){a}

This would get the compiler stuck doubling the amount of a's and turning them into b's and vice versa, so the compiler would pretty soon run out of memory and crash.

Another one is for batch on Windows, if completely freezing the computer rather than just the batch script itself counts. You should type in the following:

:a
start %0
goto a

This gets into an infinite loop of making copies of itself, which make copies of themselves and so on. This would most likely eventually crash your computer if you ran this little bit of code.

One last one is a VBS bomb. It is another bomb, like the last one, but it instead opens an infinite amount of dialog boxes.

set oshell = wscript.createobject("wscript.shell")
do
oshell.run "wscript " & wscript.scriptname
msgbox "blah"
loop

This continuously creates a copy of itself and opens up a message box in an infinite loop, which the clones do as well. Running these last two programs is not recommended, as they can freeze your computer and cause you to have to hard boot your computer.

Note that I came up with all of these programs myself.

share|improve this answer

Common Lisp, 8 bytes

Shorter than the other Common Lisp answer :-)

#.(loop)

Loop while reading your form.

The Common Lisp standard has no mention of a portable way to make it crash, so I guess we need to have an implementation-defined way. Still 8 bytes:

#.(quit) ; ccl

... or,

#.(exit) ; sbcl

When you call (compile-file "crash.lisp"), the environments mysteriously "crash".

Joking apart, I am still trying to find a way to really crash the environment (and shortly), but it is really hard. All I get is a nice interaction with the debugger.

share|improve this answer

Simplex v.0.5, 2 bytes

Too bad this isn't a :

2Q

Let me explain. From the docs:

[Q] Adds program source code to outer program, from the beginning (exclusive of ! characters, if the current byte is not zero) If byte is 2, duplicates current command as well.

So:

2 ~~ Manhattan adds 2 to the current byte: 10*0 + 2 = 2.
Q ~~ Adds program source code to the outer program, with Q

The outer program is a neat little feature in Simplex: it is evaluated at the end of the program. So, if we keep track...:

P1  P2  P3  P4  ...
2Q->2Q->2Q->2Q->...

Eventually, memory will run out and the world will end.

share|improve this answer

Clang++

I just came across this fun bug. Source link, because it's too long to reasonably post here.

The goal is to translate Brainfuck into C, using template meta-programming to do most of the work. This code works for smaller Brainfuck programs, such as Hello World, but when I tried to run it with 99 Bottles...

$ clang++ -std=c++11 -fconstexpr-depth=1000 bf_static.cpp
clang: error: unable to execute command: Segmentation fault (core dumped)
clang: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 3.5.2 (tags/RELEASE_352/final)
Target: i386-pc-windows-cygnus
Thread model: posix
clang: note: diagnostic msg: PLEASE submit a bug report to http://llvm.org/bugs/ and include the crash backtrace, preprocessed source, and associated run script.
clang: note: diagnostic msg:
********************

PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clang: note: diagnostic msg: /tmp/bf_static-afa982.cpp
clang: note: diagnostic msg: /tmp/bf_static-afa982.sh
clang: note: diagnostic msg:

********************

It will successfully compile in GCC (after about 2 minutes), but linking it causes another issue...

/usr/lib/gcc/i686-pc-cygwin/4.9.3/../../../../i686-pc-cygwin/bin/as: /tmp/cc0W7cJu.o: 
section .eh_frame$_ZN8rec_eval<giant mangled name removed>: string table overflow at offset 10004228
/tmp/cc3JeiMp.s: Assembler messages:
/tmp/cc3JeiMp.s: Fatal error: can't close /tmp/cc0W7cJu.o: File too big

Oops.

share|improve this answer

x86 asm

"nasm -v" returns "NASM version 2.11.08 compiled on Feb 21 2015" (I'm running it under win7)

The assembler has been running for 1:12:27 so far on an i7, totally saturating one of the cores. The output file is sitting at 0 bytes, memory consumption has been stable at 1,004K - it seems safe to say I've beaten nasm up, rather than just giving it a really, really long task. :)

The key to the trick is the repeat value in the macro - 0xFFFFFFFF. Though, I'm not familiar enough with Nasm's internals to know why exactly it's choking on this. I expected to get a ~16GB output an hour ago.

%MACRO INVOKE 1-*
;  %REP    %0 - 1
  %REP     0xffffffff
    %ROTATE   -1
    PUSH    DWORD %1
  %ENDREP
  %ROTATE -1
  CALL    %1
%ENDMACRO

[section .text]
bits 32
org 0x10000

EntryPoint:
    INVOKE dword 666
    ret

EDIT: Just checked the task manager, Nasm has been running for 7:40:41 and the memory is now up to 1,016K

share|improve this answer

Gnu assembler, generating huge output files

This macro attempts to fill the output file with garbage (usually null bytes) until a 4 GB boundary is reached, adds an int to get past that boundary, and recursively calls itself to keep filling the output with 4 GB chunks of garbage. This will fill your hard drive until it is full, at which point the assembler will likely crash.

.macro f n #Define a macro named f, taking argument n.
.p2align 32 #Fill file with 0x00's until current address is divisible by 2^32
.long 0 #Add a long after the current address, throwing it off alignment.
.if \n #If n > 0, recursively tail-call itself, decrementing n.
f "(\n-1)"
.endif
.endm #End macro definition.
f 32 #Expand macro f, with n = 32 (output size 4GB*32 = 128GB)

Note that infinite recursion cannot be used, as the assembler will catch that special case and stop expanding the macro.

Compilation can be done with as -o crash.out crash.s on most Linux distributions.

share|improve this answer
    
Can you comment the source? I really don't understand what this's doing. – cat Mar 28 at 15:50
1  
You should post this as an answer to Build a compiler bomb! :D – cat Mar 28 at 15:52

Common Lisp, 29 bytes

Implementation: Clozure CL

WARNING: Be careful when running this code, it may kill processes that you don't want it to!

#.(run-program"pkill"'("cl"))

This runs the shell command pkill cl on compile time, which will kill the Lisp process doing the compiling. Not technically a crash, but it has the same effect.

Example usage:

$ cat /tmp/t.lisp
#.(run-program "pkill" '("cl"))
$ ccl -n
Welcome to Clozure Common Lisp Version 1.11-dev-r16513-trunk  (LinuxX8664)!

? (compile-file "/tmp/t.lisp")
#P"/tmp/t.lx64fsl"
NIL
NIL
?
zsh: terminated  ccl -n
$ 
share|improve this answer

Felix

This doesn't work anymore, but at one point, this code:

include "std/control/pchannels";

fun is_square(v: int) => let s = int$ sqrt$ v.float + 0.5f in s*s == v;
fun is_median(v: int) => v % 4 == 0 and (v/4).is_square;

struct Message { value: int; };

proc process(c: int, chan: pchannel[Message]) {
    var i = 0;
    for var b in (c+1)/2 upto c do
        for var a in c - b + 1 upto b do
            if is_median(2*(b*b+c*c)-a*a) or
               is_median(2*(a*a+c*c)-b*b) or
               is_median(2*(a*a+b*b)-c*c) do ++i; done;
        done
    done
    write(chan, Message i);
};

proc main() {
    n := int$ System::argv 1;
    var count = n;
    chan := #mk_pchannel[Message];
    var ntri = 0;

    for var c in 1 upto n perform spawn_pthread { process(c, chan); };

    while count > 0 do
        let v = chan.read in ntri += v.value;
        --count;
    done
    ntri.println;
}

main;

This would give a big error:

inner_bind_expression raised Not_found [BUG] e=(&((main_mf_60270<60270> ())), (value v))

SYSTEM FAILURE bind_expression' raised Not_found [BUG] Felix compilation "/media/ryan/stuff/felix/build/release/host/bin/flxg" "-q" "--optimise" "--inline=100" "--output_dir=/home/ryan/stuff/.felix/text" "--cache_dir=/home/ryan/stuff/.felix/cache" "-I/media/ryan/stuff/felix/build/release/share/lib" "-I/media/ryan/stuff/felix/build/release/host/lib" "--syntax=@/media/ryan/stuff/felix/build/release/share/lib/grammar/grammar.files" "--automaton=/home/ryan/stuff/.felix/cache/media/ryan/stuff/felix/build/release/share/lib/grammar/grammar.files/syntax.automaton" "--import=plat/flx.flxh" "std" "/home/ryan/golf/itri/sl.flx" failed Error 1 in flx: [strerror_r] Failed to find text for error number 1

The issue was here:

let v = chan.read in ntri += v.value;

let expected an expression to follow it, but I put a statement instead. So the compiler freaked out a tad.

More info at https://groups.google.com/forum/m/#!topic/felix-language/J3Hs4j6E0gM.

share|improve this answer

JavaScript

while (true === true){
console.log(0);
}

This sends it into an infinite loop. I used the Codecademy JS compiler and it crashed my browser.

share|improve this answer
1  
Is that the compiler or the runtime crashing? The web browser includes both, but I'd argue they're still separate components. – Hand-E-Food Oct 16 '15 at 4:20
    
The compiler crashed, freezing my browser. @Hand-E-Food – juniorRubyist Oct 16 '15 at 4:21
1  
This is not crashing the compiler; it's hanging your webpage. Also, you could just write while(1){}; this is also an infinite loop. – SirPython Jan 15 at 1:19
    
An even shorter example is while(1);. – Aplet123 Mar 16 at 0:54

Javascript

function crash(){
  window.location.hash=Math.random(),onhashchange=function(){crash()}
}

This one crashes web browsers in a seriously effective fashion. USE AT YOUR OWN RISK!!!

share|improve this answer
3  
What is the exact means of the crash? In particular, this question is about crashing compilers, and this seems it just makes the browser die, not its JS internal compiler. – Petr Pudlák Oct 16 '15 at 18:36
    
FF refuses to crash; running this in Chrome hung my system. – cat Mar 15 at 3:59

Hassium

File1.has:

use "File2.has";

File2.has:

use "File1.has";

This causes Hassium to load and begin compiling File2.has, which tells it to load File1.has, which causes it to load File2.has, and so on.

share|improve this answer

LOLCODE 1.2, LOLCODE Common Interpreter/Compiler (lci)

I know this isn't but it's extremely short anyways.

OBTW

This causes Signal 11:

Segmentation fault (core dumped)


Why? HAI1.2 denotes the start of the program, and OBTW initiates a multiline comment. But the compiler expects a KTHXBYE to close the HAI, and a TLDR to close the multiline comment.

Note that this will still work to cause segfault with anything other than TLDR after OBTW.

(By wikipedia's standards, LOLCODE is a just a Weirdlang, not actually esoteric.)
You can grab the interpreter from git/justinmeza/lci.

share|improve this answer
    
"Use a standard language that is used in real world." Do you mean to tell me that you'd use lolcode to write a legitimate program? – Patrick Roberts Oct 17 '15 at 2:53
    
@PatrickRoberts Yes, I would. /s – VoteToSpam Oct 17 '15 at 3:19

protected by Dennis Mar 28 at 8:14

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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