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\$
  • \$\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\$ – ETHproductions Dec 23 '16 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 '16 at 22:13
  • \$\begingroup\$ 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 ? \$\endgroup\$ – Hedi Dec 23 '16 at 23:54
  • 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\$ – ETHproductions Dec 24 '16 at 1:20
  • 2
    \$\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 '16 at 11:43

102 Answers 102

1 2 3
4
1
\$\begingroup\$

Commodore BASIC (C64Mini, C64, VIC-20, C128 etc..) 32 27 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).

Self-destructing loop Commodore C64

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

BrainFuck (4 bytes)

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

| improve this answer | |
\$\endgroup\$
  • \$\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 '16 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 '16 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 '16 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 '16 at 12:55
  • \$\begingroup\$ Underflowing, then? - is enough. That makes it 4 bytes too. \$\endgroup\$ – Asu Dec 27 '16 at 22:50
0
\$\begingroup\$

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?

| improve this answer | |
\$\endgroup\$
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

| improve this answer | |
\$\endgroup\$
  • 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\$ – James Dec 26 '16 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

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
  • 3
    \$\begingroup\$ That costs ¥5? :( \$\endgroup\$ – Esolanging Fruit Mar 16 '17 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

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

k, 4 chars

,:\0

Will terminate after a few seconds with SEGV

| improve this answer | |
\$\endgroup\$
-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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ How is this any different to my answer?? \$\endgroup\$ – FlipTack Dec 24 '16 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\$ – sonrad10 Dec 24 '16 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\$ – Ismael Miguel Dec 24 '16 at 4:43
  • 2
    \$\begingroup\$ @Flp.Tkc Duplicate answers are allowed \$\endgroup\$ – Martin Ender Dec 24 '16 at 9:36
  • 3
    \$\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\$ – Ismael Miguel Dec 24 '16 at 17:27
1 2 3
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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