# 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


var QUESTION_ID=104323,OVERRIDE_USER=59718;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important;font-family:Arial,Helvetica; font-size:12px}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

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

# Commodore BASIC (C64Mini, C64, VIC-20, C128 etc..) 3227 25 tonekized BASIC bytes

0FORI=9TO0STEP-1:PRINTI/I*I:NEXT


As it counts down, it will produce a ?DIVISION BY ZERO ERROR IN 0 error before it hits 0 as is intended (old 32 byte solution shown in associated image).

### CBM BASIC (Direct mode) 9 bytes used on stack, 31 PETSCII characters

FORI=9TO0STEP-1:PRINTI/I*I:NEXT


It's a bit difficult to determine the amount of memory used in direct mode as no program is stored so that saves on those BASIC tonkenized bytes, also it executes by calling via the Kernal so that's ROM not RAM; the BASIC screen is default to 1000 bytes and direct mode outputs 1 8-bit character per line + white space + carriage return. When I request the free bytes, it tells me that I've used 9 so I'll go with that (I think that includes some memory pointers as well).

## Keg, 5 4 bytes

1{_}


After popping 1 from the stack using an infinite loop, it tries to pop from the empty stack, which terminates the loop.

# x86 Machine Code, 3 bytes

Same size on both 64 or 32 bit. 2 instructions.

a:pushf
jmp a


In 64-bit or 32-bit:

Dump of assembler code for function a:
0x0000000000001000 <+0>: 9c  pushfq
0x0000000000001001 <+1>: eb fd   jmp    0x1000 <a>
End of assembler dump.


Same machine code. Obviously, the 32-bit version won't have the extra 0's in front of the address or the q suffix.

It just runs out of stack space.

# 1+, 7 bytes

1(|:())


1+ answer delivery service, sign here.

## Explaination

1 pushes 1 onto the stack. The rest of the program (which looked like a fancy emoticon) defines a recursive function with an empty name that repeatedly pop and output the stack top, so you'll pop an empty stack the second time, which is invalid. 1+ functions are executed while defined.

# BrainFuck (4 bytes)

+[+] This will just increment the number in the current pointer until it goes over the maximum allowed size

• That won't even enter the loop since the cell is initially 0. Also, do you happen to know an interpreter that errors on overflow? – Dennis Dec 24 '16 at 0:43
• OK, bf in the Ubuntu repos seems to do this with the -w flag. Unless we find an interpreter that does this by default, you'd have to add 3 bytes to your score though. – Dennis Dec 24 '16 at 1:20
• Why 3 bytes? +[>+] works fine on most interpreters without infinite memory and is only 1 byte extra. – FinW Dec 24 '16 at 10:31
• @FinW That's not how this answer should be counted, that's how a different answer for the same language should be counted. I had posted that as an answer already before your comment, but otherwise you could've either put a comment on this answer to get user181782 to edit to make this a lower-scored answer, or posted a new answer yourself. – hvd Dec 24 '16 at 12:55
• Underflowing, then? - is enough. That makes it 4 bytes too. – Asu Dec 27 '16 at 22:50

# Python 3, 35 Bytes

x=lambda a:1/0if a<1 else x(0);x(2)


I am not totally sure, but I think this works like you'd expect. Does that count as an true answer?

for i in [1]:
print i


python code, not sure if this counts because it is ending not erring

for(var i in millis()){for(var j in millis()){for(var k in millis())for(var l in millis())println(i*j*k*l)}}}}


much longer

JavaScript code, will give a runtime error because it is running a ton of code each frame

• I'm pretty sure this is invalid because of the rule: The error must be a run-time error, unhandled exception, or anything that make the program end itself. – James Dec 26 '16 at 23:00

# QC 3 bytes

\$01

The program jumps into code at address 1, where it encounters 0, which expects 2 bytes after it, not 1. Because of that, it crashes with unexpected end of code message.

To try this code you need compile the interpreter yourself

# Bean, 4 bytes (non-competing)

5¥:(


Assembles to the JavaScript:

while(1);


Try the demo here! Running in a modern browser, this typically prompts the user within 30 seconds with a message saying

The following page(s) have become unresponsive. You can wait for them to become responsive or kill them.

• That costs ¥5? :( – Esolanging Fruit Mar 16 '17 at 6:25

# Javscript (ES6), 12 16 bytes

(a=i=>a())() // Old code, not valid

(a=i=>i?a():z) 

This produces the error: Uncaught ReferenceError: z is not defined

• "Recursion without Tail Call Optimization is invalid" – ASCII-only Jun 1 '18 at 10:59
• Sorry, forgot about that. – 77Tigers Jun 1 '18 at 11:24

# k, 4 chars

,:\0


Will terminate after a few seconds with SEGV

# Python 3, 33 16 Bytes

New code:

for i in 1,0:0/i


I realises just after posting this that a division by 1 then 0 would produce an acceptable answer, allowing me to shrink my code by more than 50%

Old code:

for i in 0,1:
if i:raise IOError

• How is this any different to my answer?? – FlipTack Dec 24 '16 at 0:32
• @Flp.Tkc I hadn't realised that someone had already posted this answer. But yes, we have taken the same approach to this. – sonrad10 Dec 24 '16 at 0:34
• Seeing that you've already realized that the aproach is the same, you should either reverte the answer or delete it. – Ismael Miguel Dec 24 '16 at 4:43
• @Flp.Tkc Duplicate answers are allowed – Martin Ender Dec 24 '16 at 9:36
• @MartinEnder Allowed or not, the downvotes will still happen. This answer is just a copy of the other, in it's majority. Nothing new here, nothing to upvote here. Might as well revert to the orgininally original answer and accept the longer byte count. – Ismael Miguel Dec 24 '16 at 17:27