63
\$\begingroup\$

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

Leaderboard:

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

\$\endgroup\$
13
  • \$\begingroup\$ 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) \$\endgroup\$ Dec 23, 2016 at 22:06
  • \$\begingroup\$ @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." \$\endgroup\$
    – Mario
    Dec 23, 2016 at 22:13
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Dec 24, 2016 at 1:20
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – BrainStone
    Dec 25, 2016 at 11:43
  • 3
    \$\begingroup\$ Voting to close because the requirements for what counts as a loop and what counts as what part of the loop are unobservable. This could sort of go either way, but I think it's vague enough that it could (and from what I've seen, has) cause disagreement about the correct interpretation. \$\endgroup\$ Jun 16, 2021 at 3:22

103 Answers 103

1 2 3
4
1
\$\begingroup\$

Zsh, 18 bytes

Abusing the short form of the for and implicit short command list. Will report "Command not found" for the first iteration, but will continue to the second and then crash.

for i (1 0) $[i/i]

Try it online!

EDIT: Boringly, for i (- exit) $i is one character shorter.

\$\endgroup\$
1
\$\begingroup\$

Julia 1.0, 12 bytes

[1,-1].|>√

This broadcasts (.|> the pipe operator with the . annotation for broadcast) the square root function over the vector [1,-1]. throws a DomainError for negative values of Real types (like Int), so this fails on the second iteration. Roughly equivalent to [√x for x in [1,-1]].

The fact that √ throws a DomainError for negative values of Real types happens to be a classic example of the design choices that allow Julia to act in many ways like a dynamic language (eg matlab, python) but generally compile to match the speed of fully typed languages (eg c, FORTRAN). It's discussed here in the Julia manual.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 15 bytes

EXEC.>SPSET(0)W
\$\endgroup\$
1
\$\begingroup\$

Java, 26 bytes

Runs out of memory after around 2-3 seconds on TIO (exactly 27 iterations)

v->{for(var a=".";;a+=a);}
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

BrainFuck (4 bytes)

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

\$\endgroup\$
5
  • \$\begingroup\$ 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? \$\endgroup\$
    – Dennis
    Dec 24, 2016 at 0:43
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – Dennis
    Dec 24, 2016 at 1:20
  • \$\begingroup\$ Why 3 bytes? +[>+] works fine on most interpreters without infinite memory and is only 1 byte extra. \$\endgroup\$
    – FinW
    Dec 24, 2016 at 10:31
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – hvd
    Dec 24, 2016 at 12:55
  • \$\begingroup\$ Underflowing, then? - is enough. That makes it 4 bytes too. \$\endgroup\$
    – asu
    Dec 27, 2016 at 22:50
0
\$\begingroup\$
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

\$\endgroup\$
1
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – DJMcMayhem
    Dec 26, 2016 at 23:00
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ That costs ¥5? :( \$\endgroup\$ Mar 16, 2017 at 6:25
0
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ "Recursion without Tail Call Optimization is invalid" \$\endgroup\$
    – ASCII-only
    Jun 1, 2018 at 10:59
  • \$\begingroup\$ Sorry, forgot about that. \$\endgroup\$
    – 77Tigers
    Jun 1, 2018 at 11:24
0
\$\begingroup\$

k, 4 chars

,:\0

Will terminate after a few seconds with SEGV

\$\endgroup\$
0
\$\begingroup\$

C

prints a - z using only 1 for loop

(which is readable, hopefully)

for(int i='a';i<='z';printf("%d\n",i),i++);

Edit: shortened even more: putchar() instead of printf

for(int i='a';i<='z';putchar(i),i++); 

working program:

#include <stdio.h>
int main() {
  for(int i='a';i<='z';putchar(i),i++);
  return 0;
}
\$\endgroup\$
2
  • \$\begingroup\$ I have tried to make it as readable as possible, (which was - also why I wrote "readable") tried to make it a bit funny too, have a great day - the one reading this message. If this can be improved(or removed? (for any reason) please feel free to say that!) thanks! //W \$\endgroup\$ Feb 16, 2021 at 18:56
  • \$\begingroup\$ This doesn't look like it would end in an error. \$\endgroup\$
    – Wezl
    Feb 17, 2021 at 14:10
-2
\$\begingroup\$

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
\$\endgroup\$
9
  • \$\begingroup\$ How is this any different to my answer?? \$\endgroup\$
    – FlipTack
    Dec 24, 2016 at 0:32
  • \$\begingroup\$ @Flp.Tkc I hadn't realised that someone had already posted this answer. But yes, we have taken the same approach to this. \$\endgroup\$
    – AvahW
    Dec 24, 2016 at 0:34
  • \$\begingroup\$ Seeing that you've already realized that the aproach is the same, you should either reverte the answer or delete it. \$\endgroup\$ Dec 24, 2016 at 4:43
  • 2
    \$\begingroup\$ @Flp.Tkc Duplicate answers are allowed \$\endgroup\$ Dec 24, 2016 at 9:36
  • 4
    \$\begingroup\$ @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. \$\endgroup\$ Dec 24, 2016 at 17:27
1 2 3
4

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