Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

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

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 make 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 on. 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
share|improve this question
    
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 20 hours ago
    
@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 20 hours ago
    
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 18 hours ago
1  
@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 17 hours ago
    
It must take no longer then 2 minutes on which computer? – Mega Man 8 hours ago

39 Answers 39

MATL, 5 1 byte

Idea taken from @MartinEnder's CJam answer

`

Try it online!

`    % Do...while loop
     % Implicit end. The loop continues if the top of the stack is true.
     % After the first iteration, since the stack is empty, the program 
     % implicitly tries to take some non-existing input, and finishes
     % with an error

Old version

2:t"x

Try it online!

2:   % Push [1 2]
t    % Duplicate
"    % For each (i.e. do the following twice)
  x  %   Delete top of the stack. Works the first time. The second it tries to
     %   implicitly take some non-existing input, and finishes with an error
share|improve this answer
1  
Works offline as well. No input means you can assume empty input. – Dennis 20 hours ago
    
@Dennis Hm the offline program will keep waiting for user input. Input is interactive, i.e. requested as needed in the offline version. So the program will wait indefinitely. Not sure that counts? – Luis Mendo 20 hours ago
    
Not exactly sure how MATL works internally, but if you execute it in an environment incapable of requesting input (such as TIO's backend), it won't be able to get any input. Also, pressing Ctrl-D or the OS-dependent equivalent should be allowed to send empty input. – Dennis 20 hours ago
    
@Dennis Thanks. Edited – Luis Mendo 20 hours ago

Python, 16 bytes

The non-interesting 0 division approach:

for x in 1,0:x/x

The first iteration computes 1 / 1, which works fine. The second iteration tries to compute 0 / 0, resulting in a ZeroDivisionError being thrown.

17 bytes (personal favourite)

i=1
while i:del i

Initially, i=1 which is truthy, so the loop is entered.

The first time the loop is run, the variable i is deleted.

This means that, the second time, i is no longer a variable and therefore its evaluation fails with NameError: name 'i' is not defined.


A 15 byte solution would be def _():_() (newline) _(), because Python does not optimize tail recursion. However, this violates rule #6.

share|improve this answer
    
The 17 bytes solution also works if you replace while i with while 1 because it tries to delete i again; – user6245072 41 mins ago
    
@user6245072 yep, both snippets can be trivially modified for lots of working solutions – Flp.Tkc 26 mins ago

Jelly, 3 2 bytes

Ṿß

Kills itself by running out of memory. Locally does so after ~100 seconds.

You can Try it online! but please don't.

How it works

Ṿß  Main link. Argument: x. Implicit first argument: 0

Ṿ   Create a string representation of x.
 ß  Recursively call the main link.
    Jelly uses TCO, so the first cycle finishes successfully before entering
    the next one.

The first few iterations yield:

'0'
'”0'
'””,”0'
'””,””,”,,””,”0'
'””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”0'
'””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”,,”,,””,”,,”,,””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”0'

After that, it gets real ugly, real fast.

share|improve this answer
    
What is jelly's memory limits? – tuskiomi 18 hours ago
    
Jelly doesn't have an explicit memory limit, so whatever Python can address. Memory usage doubles with each iteration though, so this should exhaust all available memory rather quickly. – Dennis 17 hours ago
6  
So every 2 years, we'll be able to execute another iteration – tuskiomi 17 hours ago
    
I think there is a different between (uneval) and ŒṘ (repr). – Erik the Outgolfer 9 hours ago

V, 2 bytes

òl

Try it online!

This is the perfect challenge for V because I already do that all the time! In fact, V doesn't even have any conditionals, it only has functions that break on an error. In this case, the ò means "repeat forever" and the l means "move right".

In an empty buffer (no input) this will break on the first pass and produce no output. If there is input, it will break once we move post the last character of input, and output all of the input (making this also a cat program)

share|improve this answer
    
Wait, l means "move right"? Not "move left"? – Conor O'Brien 14 hours ago
1  
@ConorO'Brien yep. There's actually some good historical reasons for this. – DJMcMayhem 14 hours ago

FALSE, 8 bytes

I really like this language.

1[$][.]#

This pushes a 1, then [$][.]# loops while $ is true (duplicate top of stack) and (.) outputs it. This interpreter crashes after the single 1 is printed (evidence of the loop running at least once.) It seems to be a bug in this interpreter. The following 9-byte program should work in all compliant interpreters:

1[$][..]#
share|improve this answer
    
You should also try DUP, which is basically a superset of FALSE. That's what I used to make RETURN. – Mama Fun Roll 15 hours ago
    
@MamaFunRoll oh yeah, I forgot that you made RETURN! I gotta try that one. :D – Conor O'Brien 15 hours ago

R, 22 25 22 20 18 bytes

Edit: Thanks to @Mego for pointing out that R does not support tail call optimization.

Edit4: Found an even shorter solution which simple yet quite intricate.

repeat(ls(T<-T-1))

The answer uses the builtin boolean truthy variable, T which is decremented indefinitely in the repeating loop. The function ls() is called each iteration which lists all objects in the current environment. However, the first argument name specifies from which environment from which to list objects. From the R-documentation we find that:

The name argument can specify the environment from which object names are taken in one of several forms: as an integer (the position in the search list); as the character string name of an element in the search list; or as an explicit environment (including using sys.frame to access the currently active function calls).

This principally means that in the first iteration we run ls(-1) which would return character(0) (standard when trying to access the non-existent everything-except-the-first element of any character type object). During the second iteration, T is decremented by two and we subsequently call ls(-3) which in turn returns the error:

Error in as.environment(pos) : invalid 'pos' argument

This is because we try to list everything-except-the-third element but the local environment only contains the variable T at this point (as such, ls() would return a list of length 1 at this iteration) and an error is returned.

share|improve this answer
1  
That doesn't sound like the recursion is done with tail call optimization, if there is a recursion limit. – Mego 19 hours ago
    
@Mego After some digging around I found out that R does indeed not support tail call optimization so this answer is not valid (never heard of the concept before). Will change to a valid answer in a moment. – Billywob 19 hours ago

JavaScript (ES6), 13 bytes

f=_=>f(_?a:1)

This is a recursive function that runs fine once, then throws ReferenceError: a is not defined and quits.

Here's a 15-byte non-ES6 version:

for(i=0;;)i=i.a

This runs fine once, then throws TypeError: i is undefined and quits.

share|improve this answer

C, 21 bytes

i;f(){for(;1/!i++;);}

Here i is guaranteed to start off as 0.

It can be confirmed that this runs once like so:

i;f(){for(;1/!i++;)puts("hi");}
main(){f();}

Which, on my machine, results in:

llama@llama:...code/c/ppcg104323loop$ ./a.out 
hi
zsh: floating point exception (core dumped)  ./a.out

The shortest recursive solution I can find is 22 bytes:

f(i){f(i-puts(""-i));}

gcc only does tail call elimination at -O2 or higher, at which point we need to call a function like puts to prevent the entire thing from being optimized away. Confirmation that this works:

llama@llama:...code/c/ppcg104323loop$ cat loop.c       
main(){f();}
f(i){f(i-puts(""-i));}
llama@llama:...code/c/ppcg104323loop$ gcc -O2 -S loop.c 2>/dev/null
llama@llama:...code/c/ppcg104323loop$ grep call loop.s
    call    puts
    call    f

The following is a full program, which assumes that it is called with no command line arguments, at 22 bytes:

main(i){for(;1/i--;);}

which is equivalent to the function of the same length:

f(i){for(i=1;1/i--;);}
share|improve this answer
    
Is a function like this treated like main? If it is, the first argument is the length of the argument list (which is 1, the name that was used to call it). – Riley 17 hours ago
    
Or, the argument register still has the value that was there from main getting called. – Riley 17 hours ago
    
@Riley Ahh, the latter theory appears to be the case, as evidenced by the fact that the number increases as command line arguments are added. Thanks for the insight! – Doorknob 17 hours ago
    
I wasn't sure how you were calling it in my first guess, but i should be the same as the first argument to the function that calls f. – Riley 17 hours ago
    
Yep, tio – Riley 17 hours ago

Bash 4.2, 22 bytes

exec $0 $@ $[2**$#%-1]

Doesn't work in TIO because it has Bash 4.3, and the bug I'm relying on was finally fixed.

Verification

$ xxd -c 22 -g 22 self-destruct
0000000: 6578656320243020244020245b322a2a2423252d315d  exec $0 $@ $[2**$#%-1]
$ ./self-destruct
Floating point exception

This crashes once the program tries to compute 263 mod -1, which crashes in Bash 4.2 and older versions due to a known bug.

share|improve this answer

CJam, 4 bytes

1{}g

Try it online!

The first iteration of the empty {}g loop pops the 1, which tells it to continue. The second iteration tries to pop another conditional, but the stack is empty, so the program crashes.

share|improve this answer

Pyth, 3 bytes

W1w

Try it online.

W1 is just while 1: in Python. The loop body prints a line read from STDIN, which crashes for the second iteration when the code is run with empty input.

If loops using # (loop-until-error) are banned (I assume so), I think this is the shortest it can get.

share|improve this answer

Python 3, 29 bytes

i=1
def x(n):del i;x(i)
x(i)

Really simple. On the second call to x, i isn't there, and Python complains about it.

share|improve this answer

Labyrinth, 3 bytes

#(/

Try it online!

Like most 2D languages, Labyrinth doesn't have any explicit looping constructs. Instead, any code that is laid out such that it is executed multiple times in a row is a loop in these languages. For the case of Labyrinth, a simple linear program acts as a loop, because the instruction pointer will bounce back and forth on it. If the program is abc (for some commands a, b and c), then the actual execution will be abcbabcbabcb... so it runs abcb in an infinite loop.

As for why this particular program crashes on the second iteration of this loop, here is what the individual commands do. Note that Labyrinth's stack contains an implicit infinite amount of zeros at the bottom:

#   Push stack depth.   [... 0]
(   Decrement.          [... -1]
/   Divide.             [... 0]
(   Decrement.          [... -1]
#   Push stack depth.   [... -1 1]
(   Decrement.          [... -1 0]
/   Divide.             Crashes with division-by-zero error.
share|improve this answer

Perl 6, 13 bytes

loop {5[$++]}

Indexes an integer literal in an infinite loop.
Relies on fact that on scalar values, the array indexing syntax can be used with index 0 (returning the value itself), but throws an Index out of range error for any other index.

share|improve this answer

Befunge-93, 3 bytes (possibly 1 or 0)

!%!

Try it online!

On the first iteration of the loop, the stack is empty, which is the equivalent of all zeros. The ! (not) operation thus converts the stack top to 1, and the % (modulo) operation calculates 0 mod 1, leaving 0. The next ! operation converts that 0 to a 1 before the program counter wraps around and begins the loop again.

On the second iteration, the first ! operations converts the 1 that is now at the top of the stack to a 0. The % operation then calculates 0 mod 0, which produces a division by zero error on the reference interpreter, and thus terminates the program.

There's also the more boring 1 byte answer, although I'm not sure if this is considered valid.

"

Try it online!

This " command starts a string, thus every space on the rest of the line is pushed onto the stack until the program counter wraps around and encounters the " again closing the string. It'll then need to wrap around a second time to repeat the process starting another string and pushing another 79 spaces onto the stack. Eventually this will either run out of memory (the reference interpreter behaviour) or produce a stack overflow.

Now if you want to really push the rules there's also technically a zero byte solution.


If you take this ruling to mean that any interpreter defines the language (as many here do), then we can assume for the moment that the Befunge language is defined by this interpreter. And one of the "features" of that interpreter is that it pushes an Undefined value onto the stack for each loop of the playfield when executing a blank program. Given enough time it will eventually run out of memory.

How fast that happens will depend on the speed of the computer, the available memory, and the browser being used. On my machine I found that Microsoft Edge worked best, but even then it was "only" using 500MB after two minutes. It wasn't until around the fifteen minute mark (with several gigabytes used) that Edge decided to kill the process and refresh the tab. So it's unlikely to make it under the two minute time limit, but with the right conditions that wouldn't necessarily be out of the question.

share|improve this answer

QBasic, 17 bytes

This code is very weird.

DO
i=11+a(i)
LOOP

How it works

In QBasic, variables are preinitialized. A regular variable without any type suffix, like i here, is preinitialized to zero.

Except if you try to subscript into that variable like an array... in which case, it's an array of 11 zeros.*

On the first time through the loop, therefore, i is 0 and a is an array. a(i) gives the zeroth element of the array (which is 0). All well and good. We set i to 11 and loop. But now 11 is not a valid index for the array a, and the program halts with Subscript out of range.

A 19-byte version that better shows what's going on:

DO
?a(i)
i=i+1
LOOP

This will print 0 eleven times before erroring.


* Conceptually, it's a 10-element array. Most things in QBasic are 1-indexed, but arrays aren't, possibly for implementation reasons. To make things work as expected for programmers, QBasic throws in an extra entry so you can use indices 1 to 10. Index 0, however, is still perfectly accessible. Go figure.

share|improve this answer
    
QBasic and arrays, where does the fun stop! – steenbergh 8 hours ago
    
Since the error doesn't have to be on the second loop, couldn't you do i=1+a(i)? – Quelklef 2 hours ago

Haskell, 15 bytes

f(a:b)=f b
f"a"

f"a" runs recursively through the string "a" by dropping the first char and eventually fails at its end with a Non-exhaustive patterns in function f exception, because f is only defined for non-empty strings.

share|improve this answer

JavaScript, 9 bytes

for(;;i);

This runs once, then throws ReferenceError: i is not defined which stops the loop.

// With a console.log(1) to see that it runs once.
for(;;i)console.log(1);

share|improve this answer
4  
I think I'm more inclined to ascribe the increment to the end of the first iteration, rather than to the beginning of second iteration or to neither iteration. I suppose this is an ambiguity of the question. – Hurkyl 19 hours ago
1  
Since for(a;b;c)d; is roughly equivalent to a;while(b){d;c;}, I'm inclined to say that the error is still thrown in the first iteration (before the loop condition is checked a second time). – ETHproductions 19 hours ago
    
@Hurkyl The first iteration begin with the initialisation, so I think that the increment should be the begining of the second iteration. – Hedi 19 hours ago

MATLAB, 18 bytes

This can be run as a script:

for j=1:2;j(j);end

The first iteration is fine, since j(1) is just 1. The second iteration crashes with an array out of bounds error, as j(2) exceeds the dimensions of j, which is a 1x1 array.

This also can be run as a script, but it only works the first time you run it. Still, it's a hilarious enough abuse of MATLAB's predefined constants that I thought I'd include it. It's also 18 bytes.

while i/i;i={};end

When run in a workspace that the variable i hasn't been defined in yet, this assumes i is the imaginary unit, so i/i = 1. In the first loop, the assignment i={} creates an empty cell array called i. On the second iteration, the loop exits with "Undefined operator '/' for input arguments of type 'cell'."

share|improve this answer

x86 assembly (AT&T syntax), 40 bytes

f:
mov $1,%eax
A:
div %eax
dec %eax
je A

Declares a function f which divides 1 by 1 on its first iteration then attempts to divide 0 by 0 and errors.

share|improve this answer
    
You can save 4 bytes by switching to Intel syntax :) – AbbKazPow 17 hours ago
3  
We usually score assembly by the size of the generated byte code, not the human-readable instructions. – Dennis 17 hours ago

GNU sed 15 Bytes

:
s/^\|a/aa/g
b

Doubles (plus 2) the length of the pattern every iteration until it runs out of memory. On my system it takes about 2 minutes to crash.


If you remove the 2 minute rule, here is a 10 byte solution:

:
s/^/a/
b
share|improve this answer

PHP, 22 bytes

This relies on PHP allowing one to give a function name to a variable and try to run it.

Also, PHP allows you to increment characters, using the increment operator. It only works on the a-z range, but is enough.

for($x=abs;++$x;)$x();

I believe this fulfills all the required points and the loop does run once.

You can see if because you will get the error Fatal error: Uncaught Error: Call to undefined function abt() in [...][...]:N.


How this works, step by step:

  • Assign abs to $x.
    Since abs is being used as a constant, PHP will check if exists.
    Since it doesn't, PHP shows a warning saying Use of undefined constant abs - assumed 'abs' (Basically: since the constant doesn't exist, it is assumed to be a string)
  • Loop the first time
    • Run the function $x().
      Since $x has the value abs, it will run the function abs().
  • Increment the value of $x.
    $x now has the value abt, instead of abs
  • Loop for the second time
    • Run the function $x().
      Since $x has the value abt, it will run the function abt().
    • The function abt() doesn't exist, killing the program at this point with a Fatal Error.
share|improve this answer

C#, 71 38 bytes

Since you provided an example in C# here another version golfed

And thanks to pinkfloydx33

void c(){checked{for(uint i=1;;i--);}}

Shorter than Parse.ToString() and even than Parse($"{c--}") I mentally dumped checked for it being too long of a keyword. Tough it certainly is shorter than Parse(c.ToString())

Original answer

class p{static void Main(){for(int c=0;;c--)uint.Parse(c.ToString());}}

This will start c=0 then decrement it, when c=-1 the uint.Parse will cause an:

Unhandled Exception: System.OverflowException: Value was either too large or too small for a UInt32.

Ungolfed version and verifying that loop runs at least once

class p {
    static void Main() {
        for(int c=0;;c--) {
            System.Console.Write(c);
            uint.Parse(c.ToString());
        }
    }
}
share|improve this answer
    
for(int c=0;;)uint.Parse($"{c--}"); – pinkfloydx33 6 hours ago
    
checked{for(uint c=1;;)c--;} – pinkfloydx33 5 hours ago
    
Ok, wow! Didn't know about the '$' shorthand! – MrPaulch 5 hours ago

Haskell, 13 bytes

f a=f$f a
f 1

Runs out of memory after a while.

share|improve this answer

Bash, 11 (Borderline non-competing)

exec $0 1$@

This script recursively execs itself, appending 1 to the args passed on each iteration. I think this counts as TCO because exec reuses the process space but doesn't eat up stack. It is borderline non-competing because it took about 10 minutes before being killed on my machine - YMMV.

share|improve this answer

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

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

share|improve this answer

><>, 3 1 byte

o

Try it here!

This is inspired by the V answer. This outputs everything on the stack until it's empty and it crashes.

Explanation

o  outputs one value from end of stack
share|improve this answer

SMBF, 5 bytes

Runs the loop once, then modifies the source code, exiting the loop. The instructions reached, in order, are: +[-<][-<\.

+[-<]

The test runs on the TIO interpreter, but you can't really check what happens. Visit the first hyperlink, which is my Python interpreter. Change the code on the data = bytearray(... line. The interpreter used to take code from STDIN, but I found that I needed non-printable input so often that changing the input in the source is easier. I also just added an option for recording what instructions were executed, which you can enable by changing debug=True.

share|improve this answer

bash, 11 bytes 10 bytes

f()(f;:);f

There's no tail-recursion to optimize away, since the last thing done in each call is the ":" command, not the recursive subcall.

This 10-byte program crashes on my MacBook in about half a second with a "fork: Resource temporarily unavailable" error.

Edit: This was 11 bytes, but I replaced the cd command with the ":" command to save a byte.


The best example I found in bash without using recursion is 20 bytes:

for((;;)){ x=x$x$x;}

This one crashes on my machine in just over a minute, due to running out of memory.


If you get rid of the 2-minute rule, presumably

for((;;)){ x=x$x;}

(18 bytes) will eventually crash due to running out of memory, but it will take a long time.


If you allow tail recursion, you can do it in 8 bytes:

f()(f);f
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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