# Shortest auto-destructive loop

Your task is to write a full program or function that takes no input and runs any type of loop (while, for, foreach, do, do-while, do-loop, goto, recursion, etc) that will end in causing an error, which means that the program must stop itself running and exit.

Rules:

1. The error must be a run-time error, unhandled exception, or anything that makes the program end itself.
2. The error must produce the stop and exit from the program without calling explicitly exit; (or equivalent) at some point.
3. Messages like Warning:, Notice:, etc, that do not cause the program to end itself are not valid. For example in PHP divisions by zero produces a Warning message but the program will not stop and will still run, this is not a valid answer.
4. The loop must run at least one full cycle. In other words the error can happen starting at the second cycle and further. This is to avoid to cause the error using incorrect code syntax: the code must be syntactically correct.
5. The loop can be even infinite (example for(;;);) if it respects the above said rules, but must take no longer than 2 minutes to end itself in a run-time error.
6. Recursion without Tail Call Optimization is invalid (1,2).
7. This is so the shortest code wins.
8. Standard loopholes are forbidden.

C# example (test online):

using System;
public class Program {
public static void Main() {
int i;
int[] n;
n = new int[5];
for(i=0; i<7; i++) {
n[i] = i;
Console.WriteLine(n[i]);
}
}
}

Output:

0
1
2
3
4
Run-time exception (line 9): Index was outside the bounds of the array.

Stack Trace:

[System.IndexOutOfRangeException: Index was outside the bounds of the array.]
at Program.Main(): line 9

Thanks to Martin Ender for the Leaderboard Snippet

• Just to be clear, recursion without TCO can be used as long as the error does not have to do with too much recursion, correct? (For example, a recursive function that errors on the second recursion) – ETHproductions Dec 23 '16 at 22:06
• @ETHproductions It was suggested by Dennis in chat: "It might be difficult to decide if a full cycle has completed in this case [of recursion]. Tail recursion kinda fits the bill, but only TCO does actually complete a cycle if execution is aborted by an error. [...] I'd say recursion without TCO is invalid." – Mario Dec 23 '16 at 22:13
• In for(a;b;c)d;, after wich statement ends the first cycle ? Is it valid to break on the first evalution of c statement ? – Hedi Dec 23 '16 at 23:54
• @Hedi Here's my humble opinion (not the OP): All entries must complete one full cycle, meaning they must enter a second cycle; this means that at least one statement is run a second time. Since the order of execution in your example is a, b, d, c, b, d, c, ..., b is the start of the cycle, and must be run at least a second time. – ETHproductions Dec 24 '16 at 1:20
• I don't want to start any trouble but since the program (of function for that matter) is not supposed to be taking any input, all recursive solutions that have a parameter are invalid because a parameter is input. – BrainStone Dec 25 '16 at 11:43

# Fuzzy Octo Guacamole, 5 bytes

11(/)

Pushes 1 twice, then starts looping. Divides the first one by the other one, consuming them. Then tries to divide 1 by 0, erroring and exiting.

# Dyalog APL, 4 bytes

*⍣=0

x0 = 0, x1 = ex0, x2 = ex1,... until two successive values are equal (i.e. never). Hits a DOMAIN ERROR on the fifth loop, as decimal128 floats overflow.

This hits the same error only on the 12361st loop (about 8 ms on my laptop):

○⍣=1

x0 = 2, x1 = x0π, x2 = x1π,... until two successive terms are equal (never).

# Perl 5, 19 12 bytes

0/$_ for 1,0 I translated sonrad10's answer to Perl. Output: Illegal division by zero at - line 1. Previously (19 bytes):$n=1;{$n/$n--;redo}

## Testing and explanation

$| = 1; # Forces print flushing, no buffering.$i = 0;     # Iteration counter for debugging.
$SIG{ALRM} = # Set SIGALRM signal handler. sub { # Anonymous subroutine, or function. die "2-second timeout reached!"; }; alarm($timeout = 2);    # SIGALRM will be sent 2 seconds from now.

##############################
### Dividing 0 / $n--... ### ############################## for (1, 0) { print 'Iteration '.++$i."; n = $_.\n"; 0 /$_;
}

Output:

Iteration 1; n = 1.
Iteration 2; n = 0.
Illegal division by zero at test.pl line 14.

# x86 machine code on DOS - 4 bytes

Played really straight:

00000000  f7 f1 e2 fc                                       |....|
00000004

Which is just:

org 100h

section .text

start:
div cx
loop start

cx starts at whatever value; loops as long as cx is not zero - and when it's zero, it crashes due to a division by zero.

Notice that this won't work directly in DosBox (whose interpreter, for reasons I don't understand, doesn't handle the CPU exception and just hangs). In a real DOS/Windows 3.11 VM (and probably in DosBox with "original" command.com) it crashes just fine.

## QBIC, 14 9 bytes

I've ported @Dlosc 's approach to QBIC, giving me a 9-byte loop-to-crash:

[12|?b(a)

This prints elements 1 through 12 of the non-existant array b and since QBasic gives us a blank 10-spaced array when first calling b(i) with a free eleventh slot (that's 10% EXTRA!), it fails on index 12.

Original answr:

[256|?chr(a)

This starts a FOR-loop that runs 256 times. On each iteration the FOR-loop counter is cast to an ASCII character and printed to screen. However, 256 is invalid in the ASCII table and CHR$() throws an error. # √ å ı ¥ ® Ï Ø ¿ , 6 bytes Note: Non-competing as language post-dates the challenge X2[P] Tries to pop from an empty list and fails ## Explanation X › Push 10 to the stack 2 › Push 2 to the stack [ › Start a for loop that iterates 2 times (pop the top value) P › Pop the top value ] › End for loop Command | Stack --------+------- X | 10 2 | 2,10 [ | 10 P | None (1st iteration) P | ERROR (2nd iteration; cannot pop from empty list) ] | None # Octave, 30 23 bytes Thanks to @StewieGriffin for golfing off 7 bytes! for i=32:35,eval(i),end Try it online! I was inspired by this Octave answer where eval was used in a similar fashion. ### Old answer for i=101:105;eval([i]);endfor Note: my Octave knowledge is very little, so my explanation might be slightly off. This for-loop completes 1 iteration, after that (on the second one) a error: 'f' undefined near line 1 column 1 is thrown. eval([number]) evaluates the ASCII literal represented by the character code. On the first iteration, it runs eval([101]), which is the same as eval(e), Euler's Constant. And so the value of e gets displayed (2.7183). On the next iteration, the program runs eval([102]), ie eval(f), and this throws and error since f is not defined. After this, the program halts and no more iterations are run. • Very clever! It can be golfed a bit: for i=32:35,eval(i),end. This evaluates a space first which does nothing. Then it tries to evaluate !, which errors. Brackets are only needed if there are several numbers eval(101), but eval([101 102 103]). endfor can be substituted with the MATLAB-style end. for i=58:60,... works too. :) – Stewie Griffin Apr 10 '17 at 10:11 # tcl, 22 time {rename time t} 2 time is a function to measure how much time is elapsed on a script. As it can receive a parameter on how many times to repeat to get the time measure of each one, it can be used has a looping mechanism. Enters the loop, executes the renaming of time command to t, then can not execute the 2nd iteration because time command went away! # tcl, 24 while 1 {rename while w} Enters the loop, executes the renaming of while command to w, then can not execute the 2nd iteration because while command went away! # tcl, 26 The for version is two more bytes longer. for {} 1 {} {rename for f} • The answer is not valid because breaks the rule #4. The loop must produce a full working cycle and the break starting from the second cycle. Your stops before. – Mario Jan 28 '17 at 8:39 • @Mario: fixed now. – sergiol Jan 29 '17 at 23:57 # Java (JDK), 26 bytes v->{for(int a=9;;a/=--a);} Try it online! Dummy division by zero at the end of the second loop. ## Credits • -1 byte thanks to Benjamin Urquhart • You can take a dummy argument (d->) to save 1 byte – Benjamin Urquhart Jun 5 '19 at 20:15 ## Haskell, 13 bytes f a=f$f a
f 1

Runs out of memory after a while.

# Sesos, 2 bytes

00000000: 0846                                              .F

Try it online!

### Sesos assembly

The binary has been generated suing the following SASM code.

nop, put, sub 1

This enters a do-while loop (nop), prints a NUL character (put), decrements the memory cell (sub 1) and starts over. In the second iteration, put tries to cast -1 to character, which fails and aborts execution with the following error message.

Invalid code point (-1) for encoding UTF-8.

# Brainfuck, 5 bytes

+[>+]

Increments the current cell. While the current cell is non-zero, move to the next cell and increment it. Since all cells start as zero, this is logically an infinite loop, but on implementations with finite tape, aborts when the end of the tape is reached. With bf:

Error: Out of range! You wanted to '>' beyond the last cell.See -c option.
an error occured

• FWIW, it will fill program memory on implementations with an infinite tape, probably til crashing. – Asu Dec 27 '16 at 22:47
• @Asu Indeed, on implementations that use finite memory to simulate an infinite tape, it will almost certainly end up crashing when memory runs out. Possibly not in the two minute limit set by the OP though. :) – hvd Dec 27 '16 at 22:52
• I've had a brainfuck interpreter running on my arduino due, it would very probably corrupt/crash something quickly enough here. On my desktop my interpreter did scroll through 16MB memory (fixed size, I don't have support for dynamic-size ones) in 0.15s, so what I have left of memory could probably be filled in 1 minute (if i'm not too sleepy for math tonight). – Asu Dec 27 '16 at 23:02
• @Asu When physical memory runs out and swapping starts, things can get horribly slow before crashing, and in real work, I've had it happen that just trying to kill the offending program took multiple minutes. But good point about the smaller devices. – hvd Dec 27 '16 at 23:05
• I don't have swapping on on my linux box because I never really needed some "burst" memory because I never use memory-intensive programs. But yeah, swapping processes will kill the reactivity of the machine. – Asu Dec 28 '16 at 14:05

# 7, 1 byte (of which only 3 bits are used)

In octal encoding:

4

In binary encoding (CP437):

ƒ

This program works as follows (as usual in my 7 demonstrations, the anonymous commands are named the same way as the corresponding named commands, and I use syntax highlighting to differentiate; bold means active, nonbold means passive):

Frame    Program   Interpretation of the program
||       4         Append 4 to the frame
||4      (empty)   Copy the last section of the frame to the program
||4      4         Swap last two frame sections, add an empty section between
|4||     (empty)   Discard last empty frame section
|4|      (empty)   Discard last empty frame section
|4       (empty)   Copy the last section of the frame to the program
|4       4         Swap last two frame sections, add an empty section between
4||      (empty)   Discard last empty frame section
4|       (empty)   Discard last empty frame section
4        (empty)   Error: program is empty, frame contains no bar

Try it online!

What we effectively have by ending the program with 4 is a loop that executes each stack element in turn, giving it itself as an argument. The initial stack contains two empty elements, so we get through two iterations before the program crashes due to a malformed stack.

## Clojure, 25 bytes

(iterate #(do(% 0)[])[0])

Implicit loop using iterate. Starts with a non-empty list, accesses the first element, then replaces the accumulator with an empty list. During the next iteration, it crashes with an index out of bounds exception when it tries to access the first element again.

This appears to be as short as it gets. I'd love to see someone beat this in Clojure.

# Java, 73 bytes

interface A{static void main(String[]a){for(int i=0;;)if(i>0)a[i++]="";}}

Will error out with ArrayIndexOutOfBoundsException.

• doesn't pass the first-loop-must pass test, since "no input is allowed" – Olivier Grégoire Dec 25 '16 at 0:20
• @KevinCruijssen How does an infinite loop result in an OutOfMemoryError? – Olivier Grégoire Jan 10 '17 at 12:02

## Lua, 11 bytes

Suprised, such a short Lua answer.

::a::goto a

On ideone it exceeds the time limit of 5 seconds, locally it freezes the interpreter window in about 5-30 seconds.

::a:: --Define GOTO point
goto a --Endlessly loop back there, without waiting.
• Any idea why it crashes? In most languages, a goto loop just runs forever without crashing. – user62131 Dec 27 '16 at 5:13

## Python 20 Bytes

def f(x=1): f(x/x-1)

When called defaults x to 1 and finds 1/1-1=0 it then finds 0/0-1 and throws an error.

• Welcome to PPCG! How about x=2 and f(1/x) (using Python 2). I also don't think you need the space after the :. – Martin Ender Dec 26 '16 at 23:47

x86 Assembly, 18 bytes

jmp start
mov eax,[esp]
ret
start:
db 90h
mov bl,91h
mov [eax],bl
jmp start

Bytes: Ù♦ï♦$├Þ¸ É│æê↑Ù¶ Hexadecimal: ['0xeb', '0x4', '0x8b', '0x4', '0x24', '0xc3', '0xe8', '0xf7', '0xff', '0xff', '0xff', '0x90', '0xb3', '0x91', '0x88', '0x18', '0xeb', '0xf4'] This is a silly method, but I like it. I'm amazed about the other answer simply using "div cx", which I didn't even think of. Anyhow, what this does is read out EIP (the instruction pointer), which points at the next byte, "db 90h". That's simply a NOP instruction, which does nothing. Before I had "inc bl", but I realized that simply changing the byte to something else is sufficient and needs two bytes less. The first time the loop runs it goes through the loop, executing the NOP. The second time the 90h is a 91h, which throws an exception. ## memes, 3 bytes n1´ Will attempt to recurse infinite times (lower -1 until its 0). n1 Negative one ´ Loop that many times This works because the looping mechanism takes the specified number, and decreases it until it is 0 – -1 therefore provides infinity. Will crash when the loop index is too large, assuming it doesn't freeze beforehand. # C#, 30 27 bytes Saved 3 bytes, thanks to milk b=>{for(int i=3;;)i/=--i;}; It runs once, and then divides zero by zero. • You can put the decrement in the loop body if you start at 3. And you don't need braces around the loop body. 27 bytes: b=>{for(int i=3;;)i/=--i;}; – milk Jan 9 '17 at 22:40 # PHP, 16 13 bytes Quite simply: while($o.=a);

Fast (original) version (16 bytes):

while($o.=a.$o);

Run like this (notices hidden because output to screen is slow):

php -d error_reporting=30709 -r 'while($o.=a);' # Explanation Just suffix a variable with a until the memory limit is exhausted (fatal error). This takes less than a minute on my machine. Original (fast) version only needs a couple (20 something) iterations because the string grows exponentially. • I'm doubting this works without changing the php.ini file. Since PHP's default time limit is 30 seconds, I think you are hitting that limit, instead of filling the memory. (30 seconds or another value by means of changing php.ini. You can read more on php.net/manual/en/function.set-time-limit.php). I will let the O.P. decide on this one. (Your old aproach will hit a limit of 134217728 bytes (128MB) in milliseconds.) – Ismael Miguel Dec 27 '16 at 16:53 • @IsmaelMiguel, the default time limit on the CLI is 0 seconds (infinite). And actually, time limit being reached is also a fatal error. – aross Dec 27 '16 at 17:00 • I still will let the O.P. decide on this one. I admit I forgot that the limit on CLI is infinite, but the answer is somewhat hardware-based: I can have a really slow machine that takes more than 2 minutes to reach the error. I do admit that the idea behind your answer is genous, but I'm not 100% convinced of it's validity. I believe that @Mario should give his opinion. – Ismael Miguel Dec 27 '16 at 19:12 • Yeah, the 2 minute mark is a bit arbitrary, but there are other answers that take longer to run than mine (20 or 30 seconds) – aross Dec 28 '16 at 8:59 • I agree with you. Just so you know, the alternative with a for loop could be for(;;)$o.=a; and with goto would be _:$o.=_;goto _;. None of those is smaller than your answer. – Ismael Miguel Dec 28 '16 at 9:30 # TI-Basic, 5 bytes Repeat ln(0:End The key here is that in TI-Basic, Repeat loops only evaluate the conditional expression starting with the second iteration. AT&T x86 assembly, 3 instructions, division by zero .global main main: div %eax dec %eax jmp main AT&T x86 assembly, 3 instructions, segfault .global main main: inc %eax mov %eax, (%eax) jmp main # Japt, 5 bytes 1/0 o Try it online! ### How it works 1/0 Infinity o Try to create the range [0..Infinity] as an array The range array consumes most of the JS engine's memory space in about 2s, and finally exits with fatal error: heap out of memory. The following would work if simple recursion was allowed. # Japt, 1 byte ß Try it online! ß calls the entire program recursively, and the infinite recursion quickly results in stack overflow. # Forth (gforth), 19 bytes : f 0 begin until ; Try it online! ### Explanation The first iteration of the loop consumes the 0 on the stack, causing the second iteration to fail with a stack-underflow while trying to grab the top of the stack. ### Code Explanation : f \ Begin a new word definition 0 \ place a 0 on the stack begin \ start an indefinite loop until \ grab the top of the stack and end the loop if not 0 ; \ end the word definition # C, 23 bytes -1 bytes thanks to ceilingcat Division by zero is boring main(){for(;;free(1));} Segfaults after the first iteration TIO # Runic Enchantments, 2 bytes `; Try it online! Repeatedly pushes a ; character onto the stack until the stack is too large and the IP begins fizzling and eventually runs out of mana and is terminated (about 24 full loops). ## Ruby, 17 bytes 2.times{|i|i/~-i} # Factor, 19 bytes 1 iota [ 0 / ] each Fails with 0 division error after 1 run. ## awk 18 bytes {while(++i/i)i-=2} or using for: {for(;++i/i;)i-=2} Test it (added print for iteration proof):$ awk '{while(++i/i){print i; i-=2}}' /dev/urandom
1
awk: cmd. line:1: (FILENAME=/dev/urandom FNR=1) fatal: division by zero attempted