Shortest auto-destructive loop

62

6

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

Mario

Posted 2016-12-23T21:45:59.430

Reputation: 3 043

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 – 2016-12-23T22:06:48.963

@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 – 2016-12-23T22:13:30.350

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 – 2016-12-23T23:54:13.530

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 – 2016-12-24T01:20:38.133

It must take no longer then 2 minutes on which computer? – Mega Man – 2016-12-24T10:09:44.953

@ETHproductions a sets variables for the first cycle. After b, d is run, c sets variables for the second cycle. Because a is specific to the first cycle, the first time c is run it's the second time that variables are set for a cycle. – Hedi – 2016-12-24T10:26:46.820

2I 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 – 2016-12-25T11:43:47.047

Exceptions are of course cases where the solution actually calls the function. – BrainStone – 2016-12-25T11:50:49.103

I'm sorry, I'm new to this and need to ask: is soft-rebooting or crashing the process a valid exit method? The rules state anything goes, pretty much, but I'm a bit shy about this. – z0rberg's – 2016-12-28T12:46:50.703

Wait, can't I do main(){int *x=malloc(1);free(x);free(x);} in C? – SIGSTACKFAULT – 2017-02-14T17:44:12.753

Answers

33

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

Luis Mendo

Posted 2016-12-23T21:45:59.430

Reputation: 87 464

3Works offline as well. No input means you can assume empty input. – Dennis – 2016-12-23T22:29:14.973

@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 – 2016-12-23T22:32:13.353

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 – 2016-12-23T22:34:41.683

35

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.


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

FlipTack

Posted 2016-12-23T21:45:59.430

Reputation: 13 242

The 17 bytes solution also works if you replace while i with while 1 because it tries to delete i again; – user6245072 – 2016-12-24T17:56:26.323

2@user6245072 yep, both snippets can be trivially modified for lots of working solutions – FlipTack – 2016-12-24T18:11:13.123

You can use your del trick with a built-in to shave off a few more: while 1:del id. – DSM – 2016-12-24T21:02:22.397

@DSM: del id doesn't work. You can't delete builtins that way.

– user2357112 supports Monica – 2016-12-28T03:34:49.310

18

Jelly, 3 2 bytes

Ṿß

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

Try it online! (death certificate in Debug drawer)

How it works

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

Ṿ   Uneval; yield 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.

Dennis

Posted 2016-12-23T21:45:59.430

Reputation: 196 637

What is jelly's memory limits? – tuskiomi – 2016-12-24T00:09:45.397

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 – 2016-12-24T00:40:48.280

29So every 2 years, we'll be able to execute another iteration – tuskiomi – 2016-12-24T00:43:09.353

So will fail condition #5 on slow machine with lots of RAM? – Mad Physicist – 2016-12-27T22:18:58.910

@MadPhysicist That is correct. This is a inherent problem with time limits though. Compliance depends very much on which machine the program is run. – Dennis – 2016-12-27T22:22:35.713

13

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)

James

Posted 2016-12-23T21:45:59.430

Reputation: 54 537

3Wait, l means "move right"? Not "move left"? – Conor O'Brien – 2016-12-24T03:50:21.050

1

@ConorO'Brien yep. There's actually some good historical reasons for this.

– James – 2016-12-24T03:53:16.197

3The challenge requires answers to crash on the second iteration or later, not on the first iteration. – Martin Ender – 2016-12-26T13:44:06.540

11

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.

ETHproductions

Posted 2016-12-23T21:45:59.430

Reputation: 47 880

10

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.

Dennis

Posted 2016-12-23T21:45:59.430

Reputation: 196 637

10

GNU sed, 15 13 5 bytes

-2 Thanks to seshoumara
-8 Thanks to zeppelin

H;G;D
  1. Appends a newline and the hold space to the pattern space.
  2. Appends a newline and the pattern space to the hold space.
  3. Deletes up to the first newline and starts over.

This quickly runs out of memory:

$ time (echo|sed 'H;G;D')
sed: couldn't re-allocate memory

real    0m1.580s
user    0m0.545s
sys     0m1.012s

Riley

Posted 2016-12-23T21:45:59.430

Reputation: 11 345

Hi, how about s:a\?:&a:g? It is 1 byte less and doubles the pattern size per iteration as well. – seshoumara – 2017-02-03T15:48:34.077

@seshoumara I don't think that'll match anything when the pattern space is empty, so it'll never make the first replacement. – Riley – 2017-02-03T15:54:22.540

@seshoumara echo -n | sed 's:a\?:&a:g' and got no output. It would be the same as sed 's::a:' which wouldn't match anything. – Riley – 2017-02-03T16:25:01.377

With echo -n absolutely nothing gets passed to sed, but sed can't start without input by design. Check this meta link to see that echo|sed is the accepted way to start sed for challenges invoking a no input rule.

– seshoumara – 2017-02-03T16:33:54.750

@seshoumara I thought it would still give it an empty string. That seems to work then. Thanks! – Riley – 2017-02-03T16:39:49.393

You can save 6 more bytes, by replacing your s/// command with H;G, as explained here

– zeppelin – 2017-02-03T19:24:33.993

10

PHP, 22 21 20 18 bytes

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

This simply concatenate the name of the pi function twice. This kills PHP with a Fatal Error: Uncaught Error: Call to undefined function pipi() in [...][...].

while($x.=pi)$x();

This works similar to my old answer.


Old answer, 20 bytes

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

for($x=pi;;)$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: Function name must be a string.


How this works, step by step:

  • Assign pi to $x.
    Since pi is being used as a constant, PHP will check if exists.
    Since it doesn't, PHP shows a warning saying Use of undefined constant pi - assumed 'pi' (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 pi, it will run the function pi().
  • Store the value in $x.
    $x now has π, instead of pi
  • Loop for the second time
    • Run the function $x().
      Since $x has π, it will run the function 3.14159...().
    • π isn't a string, killing the program at this point with a Fatal Error.

Thanks to @Titus for finding the pi() function, saving me 1 byte!

Ismael Miguel

Posted 2016-12-23T21:45:59.430

Reputation: 6 797

Nice one, but I don't think it's valid. It doesn't really run the loop once. You increment $x to abt before the loop body runs. You could fix that by incrementing after the loop. – aross – 2016-12-27T14:56:45.540

I thought of a different approach

– aross – 2016-12-27T15:22:10.323

@aross Duh, You're right, it wasn't valid. The increment is in the wrong place. It is working as it should now. You can try to run for($x=abs;;++$x)echo$x,$x(); to test. It should show abs0abt Fatal error[...]. Or similar. – Ismael Miguel – 2016-12-28T09:52:13.147

1You could use pi instead of abs. That doesn´t even yield a warning before it throws the fatal. – Titus – 2017-01-09T16:39:38.180

@Titus I completelly forgot about that function! I know that the function _ is defined in some systems, but is unreliable. But thank you for finding that! – Ismael Miguel – 2017-01-09T18:36:27.597

_ is an alias for [gettext](http://php.net/function-gettext), requires GNU gettext and --with-gettext[=DIR]`. BUT: Increment has no effect on the underscore. – Titus – 2017-01-09T18:43:52.267

That's something I didn't try.. But I've saved another byte with your finding – Ismael Miguel – 2017-01-09T19:24:03.963

9

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.

Billywob

Posted 2016-12-23T21:45:59.430

Reputation: 3 363

1That doesn't sound like the recursion is done with tail call optimization, if there is a recursion limit. – Mego – 2016-12-23T23:15:00.437

@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 – 2016-12-23T23:22:36.340

9

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.

James Holderness

Posted 2016-12-23T21:45:59.430

Reputation: 8 298

8

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--;);}

Doorknob

Posted 2016-12-23T21:45:59.430

Reputation: 68 138

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 – 2016-12-24T00:40:34.873

Or, the argument register still has the value that was there from main getting called. – Riley – 2016-12-24T00:47:14.853

@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 – 2016-12-24T01:02:22.710

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 – 2016-12-24T01:08:15.563

Yep, tio

– Riley – 2016-12-24T01:11:39.763

8

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[$][..]#

Conor O'Brien

Posted 2016-12-23T21:45:59.430

Reputation: 36 228

You should also try DUP, which is basically a superset of FALSE. That's what I used to make RETURN. – Mama Fun Roll – 2016-12-24T03:04:56.857

@MamaFunRoll oh yeah, I forgot that you made RETURN! I gotta try that one. :D – Conor O'Brien – 2016-12-24T03:12:49.263

@MamaFunRoll I love DUP, I just wrote a DUP interpreter and I’m playing around with it. – M L – 2016-12-27T18:20:03.320

@ConnorO'Brien: I would say that your first solution should crash any interpreter. I just made a debug run with my own interpreter, and it’s obvious that the first . empties the data stack, while in the second loop $ tries to duplicate the top element of the empty stack, which should lead to an error (well, my interpreter does).

The second version should not be valid because it does not even finish the first loop because it already tries to access the empty stack prematurely. – M L – 2016-12-27T18:36:49.867

For your second example, Here’s a full colored debug Dump of my DUP interpreter. it’s obvious once you see how the data stack (ds) and the return stack (rs) work, the latter not being transparent in FALSE, though.

– M L – 2016-12-27T19:00:01.903

6

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'."

MattWH

Posted 2016-12-23T21:45:59.430

Reputation: 331

Both of those are awesome! You probably know this, but j(2) would normally give a 2-by-2 matrix with 0+1i – Stewie Griffin – 2017-04-10T10:18:23.923

Thanks! That's true in Octave but not in MATLAB I think – MattWH – 2017-04-11T20:25:37.777

6

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.

smls

Posted 2016-12-23T21:45:59.430

Reputation: 4 352

6

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.

DLosc

Posted 2016-12-23T21:45:59.430

Reputation: 21 213

QBasic and arrays, where does the fun stop! – steenbergh – 2016-12-24T09:59:30.027

Since the error doesn't have to be on the second loop, couldn't you do i=1+a(i)? – Quelklef – 2016-12-24T15:40:59.590

@Quelklef No, you'd have to do i=i+1+a(i). Otherwise the index never gets above 1, which isn't an error. – DLosc – 2016-12-24T19:31:47.833

@DLosc Oh, you're right. – Quelklef – 2016-12-25T21:25:33.480

5

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.

nimi

Posted 2016-12-23T21:45:59.430

Reputation: 34 639

5

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());
        }
    }
}

MrPaulch

Posted 2016-12-23T21:45:59.430

Reputation: 771

for(int c=0;;)uint.Parse($"{c--}"); – pinkfloydx33 – 2016-12-24T12:24:23.833

1checked{for(uint c=1;;)c--;} – pinkfloydx33 – 2016-12-24T12:38:53.320

Ok, wow! Didn't know about the '$' shorthand! – MrPaulch – 2016-12-24T12:58:59.413

4

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.

Martin Ender

Posted 2016-12-23T21:45:59.430

Reputation: 184 808

4

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);

Taking the following as an example, is the <increment> the end of the first cycle or the beginning of the second cycle ?

0:for(<init>;<test>;<increment>)
1:{
2:  <statement>;
3:}

1/ I see it

After going from lines 0 to line 3 then going back to line 0, it feels like a full cycle has been completed.
That would make the <increment> the beginning of the second cycle.
- First cycle : <init> -> <test> -> <statement>
- Second cycle : <increment> -> <test> -> <statement>

2/ While equivalent

0:<init>;
1:while(<test>)
2:{
3:  <statement>;
4:  <increment>;
5:}

In this equivalent while the <increment> is the end of the first cycle and it feels like it's the same with the for.
That would make the <increment> the end of the first cycle.
- First cycle : <test> -> <statement> -> <increment>
- Second cycle : <test> -> <statement> -> <increment>

3/ A statement is encountered twice

A full cycle is completed when a statement is encountered twice.
The first statement encountered twice is <test>.
That would make the <increment> the end of the first cycle.
- First cycle : <test> -> <statement> -> <increment>
- Second cycle : <test> -> <statement> -> <increment>

4/ It's a setup

The <init> is just setting up whatever is needed for the first cycle.
The <increment> is just setting up whatever is needed for the second cycle.
That would make the <increment> the beginning of the second cycle.
- First cycle : <init as a setup> -> <test> -> <statement>
- Second cycle : <increment as a setup> -> <test> -> <statement>


The ECMAScript® 2016 Language Specification

Runtime of for(<init>;<test>;<increment>)<statement>;

Let varDcl be the result of evaluating <init>.
ReturnIfAbrupt(varDcl).
Return ? ForBodyEvaluation(<test>, <increment>, <statement>, « », labelSet).

There are three forms, so I took the shortest one here, there's no difference:
- Whatever the <init> it isn't part of the first iteration.
- What's relevant is in ForBodyEvaluation.

Details of ForBodyEvaluation(<test>, <increment>, <statement>, « », labelSet)

0 Let V be undefined.
1 Perform ? CreatePerIterationEnvironment(perIterationBindings).
2 Repeat
3  If is not [empty], then
4   Let testRef be the result of evaluating <test>.
5   Let testValue be ? GetValue(testRef).
6   If ToBoolean(testValue) is false, return NormalCompletion(V).
7  Let result be the result of evaluating <statement>.
8  If LoopContinues(result, labelSet) is false, return Completion(UpdateEmpty(result, V)).
9  If result.[[Value]] is not empty, let V be result.[[Value]].
10  Perform ? CreatePerIterationEnvironment(perIterationBindings).
11  If is not [empty], then
12   Let incRef be the result of evaluating <increment>.
13   Perform ? GetValue(incRef).

6/ I see it

A full cycle a full run of the repeat part.
That would make the <increment> the end of the first cycle.
- First cycle : <test> -> <statement> -> <increment> / In other words from line 3 to line 13
- Second cycle : <test> -> <statement> -> <increment> / In other words from line 3 to line 13

7/ A cycle is an iteration

A cycle begin with CreatePerIterationEnvironment.
So when CreatePerIterationEnvironment is encountered a new cycle begins, thus ending the previous one.
That would make the <increment> the beginning of the second cycle.
- First cycle : <test> -> <statement> / In other words from line 1 to line 9
- Second cycle : <increment> -> <test> -> <statement> / In other words from line 10 looping until line 9


Is the <increment> the end of the first cycle or the beginning of the second cycle?

The right explanation is either 6 or 7.

Hedi

Posted 2016-12-23T21:45:59.430

Reputation: 1 857

8I 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. – None – 2016-12-23T22:46:00.557

1Since 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 – 2016-12-23T22:54:28.477

@Hurkyl The first iteration begin with the initialisation, so I think that the increment should be the begining of the second iteration. – Hedi – 2016-12-23T22:57:53.513

4

If you read the spec, you can see that the increment operation is the last part of the iteration and as such, still belongs in the first iteration.

– Nit – 2016-12-26T14:19:59.037

@Nit CreatePerIterationEnvironment is done once before the repeat section to set the environnement for the first iteration, and in the repeat section you find another CreatePerIterationEnvironment, just before the increment. So the increment run with the environnement of the second iteration. If the increment was part of the first iteration the CreatePerIterationEnvironment would appear only once and be the first operation of the repeat section. – Hedi – 2016-12-26T19:20:01.060

3@Hedi I don't see how that is relevant at all. The increment operation is very clearly a part of the first run of the loop. To rephrase, when the increment operation is called, the loop has not finished a single full run. – Nit – 2016-12-26T19:32:16.617

4

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.

poi830

Posted 2016-12-23T21:45:59.430

Reputation: 1 265

You can save 4 bytes by switching to Intel syntax :) – mriklojn – 2016-12-24T01:08:58.657

6We usually score assembly by the size of the generated byte code, not the human-readable instructions. – Dennis – 2016-12-24T01:35:55.730

@Dennis assmebled assembly is machine language. but yeah this could be claimed much shorter in machine language form. – Jasen – 2016-12-25T02:51:12.637

Get rid of the f-label and the mov. Swap the dec and div, and you can get rid of even more. – Clearer – 2017-01-27T20:39:39.160

4

><>, 3 bytes

!]!

Try it here!

Explanation

!    skip next instruction
 ]   close stack (crash)
  !  skip next instruction (jumping to close stack)

redstarcoder

Posted 2016-12-23T21:45:59.430

Reputation: 1 771

4

INTERCAL, 12 bytes

(1)DO(1)NEXT

Try it online!

NEXT is INTERCAL-72's main control flow command. (Later revisions introduced COME FROM, which became more famous, but it wasn't in the original version of the language; and all finished INTERCAL implementations I'm aware of support NEXT for backwards compatibility, with all but one enabling support for it by default. So I don't feel the need to name INTERCAL-72 specifically in the title.)

When using NEXT to form a loop, you're supposed to use RESUME or FORGET in order to free up the space that it uses to remember where the program has been; RESUME retroactively makes the NEXT into something akin to a function call (although you can return from functions other than the one you're in) whereas FORGET makes it into something more similar to a GOTO statement. If you don't do either (and this program doesn't), the program will crash after 80 iterations (this behaviour is actually specified in the INTERCAL specification).

It's somewhat ambiguous whether this counts as unbounded recursion (disallowed in the question); you can certainly use this sort of NEXT to implement a function call, in which case it would effectively be a recursive function, but there's not enough information here to determine whether we're doing a function call or not. At least, I'm posting this anyway because it doesn't unambiguously violate the rules, and an INTERCAL implementation that optimized out the "tail call" would not only violate the specification, but also cause most existing programs to break, because returning from the "wrong function" is the main way to do the equivalent of an IF statement.

Here's the resulting error message, as generated by C-INTERCAL:

ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON
    ON THE WAY TO 1
        CORRECT SOURCE AND RESUBNIT

(Note that the second line is indented with a tab, and the third with eight spaces. This looks correct in a terminal, or in pretty much any program that has tab stops at multiples of 8. However, Markdown has tab stops at multiples of four, violating the assumptions that most older programs make about tabs, so the error message is a little malformatted here.)

user62131

Posted 2016-12-23T21:45:59.430

Reputation:

Does the error really say CORRECT SOURCE AND RESUBNIT? As in a typo in the original C-INTERCAL error message? – Andrakis – 2016-12-25T05:37:52.440

1@Andrakis: Yes, it does. That typo's been carefully preserved for years. – None – 2016-12-25T12:35:27.087

4

CJam, 4 bytes

P`:~

P` generates the string 3.141592653589793. :~ evaluates each character. 3 is valid code in CJam which simply returns 3. In the next iteration, . causes an error because it requires a digit or an operator following it.

jimmy23013

Posted 2016-12-23T21:45:59.430

Reputation: 34 042

4

Ruby, 14 Bytes

loop{$./=~$.}

Exits due to ZeroDivisionError: divided by 0

$. The current input line number of the last file that was read

Ruby Docs

Jatin Dhankhar

Posted 2016-12-23T21:45:59.430

Reputation: 141

4

Batch, 22 20 bytes

:a
set i=%i%1
goto a

Explanation

This is an infinite loop that appends a 1 onto an initially empty string. Eventually this will pass the maximum string length of 8192 and crash. On my machine, this takes about 30 seconds.

SomethingDark

Posted 2016-12-23T21:45:59.430

Reputation: 211

Nice! You can save 2 bytes by using Unix line endings. – briantist – 2016-12-27T00:49:10.490

You can use %0 which is the filename instead of the label and goto. – YourDeathIsComing – 2017-01-01T18:14:19.153

I wasn't sure if that broke the tail recursion rule. – SomethingDark – 2017-01-01T18:15:42.337

3

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.

PurkkaKoodari

Posted 2016-12-23T21:45:59.430

Reputation: 16 699

3

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.

python-b5

Posted 2016-12-23T21:45:59.430

Reputation: 89

3

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.

Martin Ender

Posted 2016-12-23T21:45:59.430

Reputation: 184 808

3

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.

Digital Trauma

Posted 2016-12-23T21:45:59.430

Reputation: 64 644

1exec $0 1$@$@ terminates much faster but is two characters longer. – Jasen – 2016-12-25T02:54:15.557

3

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.

steenbergh

Posted 2016-12-23T21:45:59.430

Reputation: 7 772

3

cmd, 34 bytes

for /l %i in (0,1,10) do color %i0

This will cycle %i from 0 to 10. The (ancient) color command will happily accept any argument that has 2 (hexa-)decimal digits. With the argument 100 it will fail, printing the the help message and setting ERRORLEVEL to 1.

Proof of the loop running at least once: The color of your shell will be different!

MrPaulch

Posted 2016-12-23T21:45:59.430

Reputation: 771

3

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.

user41805

Posted 2016-12-23T21:45:59.430

Reputation: 16 320

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 – 2017-04-10T10:11:05.717

3

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

Olivier Grégoire

Posted 2016-12-23T21:45:59.430

Reputation: 10 647

You can take a dummy argument (d->) to save 1 byte – Benjamin Urquhart – 2019-06-05T20:15:48.467

3

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).

Adám

Posted 2016-12-23T21:45:59.430

Reputation: 37 779

3

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.

Rɪᴋᴇʀ

Posted 2016-12-23T21:45:59.430

Reputation: 7 410

3

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.

g4v3

Posted 2016-12-23T21:45:59.430

Reputation: 241

3

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.

crash in Windows 311 DOS Window

Matteo Italia

Posted 2016-12-23T21:45:59.430

Reputation: 3 669

3

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}

sergiol

Posted 2016-12-23T21:45:59.430

Reputation: 3 055

1The 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 – 2017-01-28T08:39:58.243

1@Mario: fixed now. – sergiol – 2017-01-29T23:57:11.027

3

√ å ı ¥ ® Ï Ø ¿ , 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

caird coinheringaahing

Posted 2016-12-23T21:45:59.430

Reputation: 13 702

2

Haskell, 13 bytes

f a=f$f a
f 1

Runs out of memory after a while.

poi830

Posted 2016-12-23T21:45:59.430

Reputation: 1 265

2

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.

Dennis

Posted 2016-12-23T21:45:59.430

Reputation: 196 637

2

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

hvd

Posted 2016-12-23T21:45:59.430

Reputation: 3 664

1FWIW, it will fill program memory on implementations with an infinite tape, probably til crashing. – Asu – 2016-12-27T22:47:12.580

@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 – 2016-12-27T22:52:34.440

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 – 2016-12-27T23:02:17.160

@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 – 2016-12-27T23:05:05.853

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 – 2016-12-28T14:05:30.853

2

Java, 73 bytes

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

Will error out with ArrayIndexOutOfBoundsException.

Roman Gräf

Posted 2016-12-23T21:45:59.430

Reputation: 2 915

1doesn't pass the first-loop-must pass test, since "no input is allowed" – Olivier Grégoire – 2016-12-25T00:20:13.483

@KevinCruijssen How does an infinite loop result in an OutOfMemoryError? – Olivier Grégoire – 2017-01-10T12:02:05.243

2

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.

user62131

Posted 2016-12-23T21:45:59.430

Reputation:

2

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.

Carcigenicate

Posted 2016-12-23T21:45:59.430

Reputation: 3 295

2

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.

devRicher

Posted 2016-12-23T21:45:59.430

Reputation: 1 609

1Any idea why it crashes? In most languages, a goto loop just runs forever without crashing. – None – 2016-12-27T05:13:05.653

2

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.

Donald Hobson

Posted 2016-12-23T21:45:59.430

Reputation: 121

3Welcome 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 – 2016-12-26T23:47:05.720

2

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.

devRicher

Posted 2016-12-23T21:45:59.430

Reputation: 1 609

2

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.

aross

Posted 2016-12-23T21:45:59.430

Reputation: 1 583

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 http://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 – 2016-12-27T16:53:50.787

@IsmaelMiguel, the default time limit on the CLI is 0 seconds (infinite). And actually, time limit being reached is also a fatal error.

– aross – 2016-12-27T17:00:29.150

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 – 2016-12-27T19:12:13.003

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 – 2016-12-28T08:59:35.130

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 – 2016-12-28T09:30:06.310

2

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.

Horváth Dávid

Posted 2016-12-23T21:45:59.430

Reputation: 679

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 – 2017-01-09T22:40:54.803

2

x86 Assembly, 18 bytes

jmp start
ReadEIP:
mov eax,[esp]
ret
start:
call ReadEIP
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.

z0rberg's

Posted 2016-12-23T21:45:59.430

Reputation: 409

2

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.

Timtech

Posted 2016-12-23T21:45:59.430

Reputation: 12 038

2

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

Clearer

Posted 2016-12-23T21:45:59.430

Reputation: 121

2

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.

Bubbler

Posted 2016-12-23T21:45:59.430

Reputation: 16 616

2

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

reffu

Posted 2016-12-23T21:45:59.430

Reputation: 1 361

2

C, 23 bytes

-1 bytes thanks to ceilingcat
Division by zero is boring

main(){for(;;free(1));}

Segfaults after the first iteration

TIO

Benjamin Urquhart

Posted 2016-12-23T21:45:59.430

Reputation: 1 262

2

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).

Draco18s no longer trusts SE

Posted 2016-12-23T21:45:59.430

Reputation: 3 053

1

Ruby, 17 bytes

2.times{|i|i/~-i}

G B

Posted 2016-12-23T21:45:59.430

Reputation: 11 099

1

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.

mbomb007

Posted 2016-12-23T21:45:59.430

Reputation: 21 944

1

bash (No recursion), 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.


I had originally posted a recursive solution in 10 bytes:

f()(f;:);f

This 10-byte program crashes on my MacBook in about half a second with a "fork: Resource temporarily unavailable" error. There's no tail-recursion to optimize away, since the last thing done in each call is the ":" command, not the recursive subcall.

But @Dennis pointed out that this doesn't satisfy Rule 4 (the program must complete one full cycle), since none of the recursive calls actually get a chance to complete before the program crashes.

I think this same problem invalidates other recursive programs that have been posted as answers.


By the way, if you allow tail recursion, you can do it in 8 bytes:

f()(f);f

[This version doesn't satisfy the tail-call-optimization requirement, and it's arguable whether it satisfies the one-complete-cycle rule. The function calls (except for the last) execute all of the code in their body, but they don't ever return. So if "one complete cycle" means one complete body, not including the return at the end, it's OK for Rule 4. If "one complete cycle" is taken to include the return at the end, then Rule 4 is not satisfied.]

Mitchell Spector

Posted 2016-12-23T21:45:59.430

Reputation: 3 392

I think you missed the point regarding tail recursion. Tail call optimization is mandatory in this challenge if you use any kind of recursion. This is because rule 4 dictates that the iteration has to complete at least one cycle. In both of your recursive solutions, the outmost function never finishes because the function it calls never returns. – Dennis – 2016-12-24T21:56:59.980

@Dennis You may be right, but I think it's a bit unclear. The tail-call-optimization rule (Rule #6) is separate from the one-full-cycle rule (Rule #4). Rule #6 is followed: there is no tail recursion, so tail-call-optimization isn't a question. Rule #4 may be an issue though. It's true that no recursive subcall gets a chance to return. But it's not clear that that's the right way to count loop iterations in a recursive program. OP allowed recursive programs; how did he intend for a recursive program to qualify? (OP's stated reason for Rule #4 is just to avoid errors due to incorrect syntax.) – Mitchell Spector – 2016-12-25T03:41:48.543

@Dennis I'll be rewriting my answer to take the issues into account -- thanks for the input. – Mitchell Spector – 2016-12-25T03:49:04.850

1

Factor, 19 bytes

1 iota [ 0 / ] each

Fails with 0 division error after 1 run.

cat

Posted 2016-12-23T21:45:59.430

Reputation: 4 989

1

Go, 28 bytes

func f(){i:=1;for{i/=i;i--}}

Simple divide by zero

Eric Lagergren

Posted 2016-12-23T21:45:59.430

Reputation: 473

1You did yourself a nice go-around the rules, pretty impressed. – devRicher – 2016-12-25T22:37:50.410

1

Mathematica, 22 19 bytes

3 bytes saved due to Martin Ender.

#>0&&Throw@#&/@{0,}

Uses Throw@# to throw an exception when looping over the second element. I can't think of anything else that would cause the program to immediately stop.

LegionMammal978

Posted 2016-12-23T21:45:59.430

Reputation: 15 731

1

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

James Brown

Posted 2016-12-23T21:45:59.430

Reputation: 663

1

Turtlèd, 6 bytes

runs one cycle before crashing. however it produces no output, because the interpreter does the crash before it prints the grid.

[|(*r]

Tryitonline can show you the error in debug, but won't really show you whether it runs the loop one cycle and a half, but if you want, you could download the interpreter, modify command ] to print howdy or something, and see that it prints howdy prior to crashing.

yes, the parentheses is usually in pairs for ifs. looks like a syntax error, but my language checks no syntax

How it works:

So this is a turtle based language, moving around on an infinite grid of cells with chars in

Firstly, there is the infinite loop

[|   ]

this loop runs while the cell does not have a |. There is no way that a cell will contain a |, since no code in this writes it or user input down, so this would run forever (except error)

The code inside:

(*r

the (* would usually starts an if block. essentially, if the current cell is a *, do nothing and continue running, otherwise skip ahead to the matching ), and the r just makes the pointer move right.

on the first cycle, the turtle starts in the centre cell, which unlike other cells, begins as an *.

here are the steps of execution from there

  • the infinite loop starts running.
  • checks the current cell to see if it is an asterisk, sees it is
  • moves right, off the asterisk cell
  • loops back to the start of loop
  • checks if cell is an asterisk. it is a space, so it tries to skip ahead
  • interpreter throws IndexError, because it tried to look past the end of the loop for the closing )

Destructible Lemon

Posted 2016-12-23T21:45:59.430

Reputation: 5 908

1

Valve Scripting Language, 21 bytes

alias a "alias a b;a"

This creates a function that will recurse when called. You can call the function just by typing 'a' into the console.

Since this challenge wants an error to be thrown, b is sufficient. This will just error with undefined function. However, you can also replace b with quit to fully quit the application.

Explanation for those who don't immediately understand: it re-aliases the function to something that doesn't exist.

Rɪᴋᴇʀ

Posted 2016-12-23T21:45:59.430

Reputation: 7 410

1

Bash, 21 bytes

alias a="alias a=c;a"

Same logic as my VSL answer, posted for completeness.

Rɪᴋᴇʀ

Posted 2016-12-23T21:45:59.430

Reputation: 7 410

1

PowerShell, 18 bytes

0,1|%{rv ~ -ea $_}

Try it online!

Explanation

An array with two elements, 0 and 1, is piped into ForEach-Object (%). Within the loop we try to remove a non-existant variable named ~ (it could have been named anything that doesn't exist).

By default this is a non-terminating error, but we're setting the -ErrorAction (-ea) to be equal to the loop object. So on the first run it's 0 which corresponds to SilentlyContinue (it won't even show the error text), then on the second run it's 1 which corresponds to Stop; this makes the error terminating, so the program will exit since this exception is unhandled.

briantist

Posted 2016-12-23T21:45:59.430

Reputation: 3 110

1

Ruby, 11 bytes

loop{$.*=2}

$. needs to be a long, so it will throw after a couple cycles.

Borsunho

Posted 2016-12-23T21:45:59.430

Reputation: 261

1

Julia, 19 bytes

for i=1:2 "a"[i]end

The first loop accesses string "a" at index [1], which is char 'a', the second loop tries to access string "a" at index [2] and throws a BoundsError:

julia> for i=1:2 "a"[i]end
ERROR: BoundsError: attempt to access 1-element Array{UInt8,1} at index [2]
 in next at .\strings\string.jl:88 [inlined]
 in getindex(::String, ::Int64) at .\strings\basic.jl:70
 in macro expansion; at .\REPL[40]:1 [inlined]
 in anonymous at .\<missing>:?

M L

Posted 2016-12-23T21:45:59.430

Reputation: 2 865

1

DUP, 10 bytes (8 chars)

Conor O'Brien already wrote the shortest possible solution in FALSE which is also a valid DUP program. DUP is a direct descendant of FALSE and FALSE is almost a complete subset of DUP, with a few exceptions. I won’t just simply rip off his solution but add a slightly bigger (in bytes, not chars) but specific DUP solution just for the fun of it:

1[.A]⇒AA

In contrast to FALSE, DUP can define/redefine operators with the (3 UTF-8 byte) operator. Operator names are not bound to the lowercase ASCII range of variables but can use the whole Unicode range of characters.

This solution is a recursive operator call that throws an error after the first recursive call of itself:

1[.A]⇒AA     data   return
             stack  stack

1                            push 1 on data stack
 [           1               push [ location on data stack, move behind matching ]
     ⇒A       1,1            pop data stack, assign value (function location) to function A
       A      1              call function A, push current ip location on return stack,
                             move ip 1 behind stored address in A (1)
  .           1      7       pop data stack, print value to STDOUT
   A                         call function A, move ip 1 behind stored address
  .                          pop data stack... throws error because the data stack is empty.

Try it out in the online DUP interpreter on quirkster.com or clone my DUP interpreter repository on GitHub (written in Julia).

M L

Posted 2016-12-23T21:45:59.430

Reputation: 2 865

1

Kotlin, 19 bytes

{for(x in-1..0)1/x}

A simple lambda expression that does one iteration of the for loop and then throws with a division by zero exception.

TheNumberOne

Posted 2016-12-23T21:45:59.430

Reputation: 10 855

1

Euphoria - 53 bytes

atom i
i=1
while 1 do
puts(i,i)
i-=1
end while

Did it in a different way so we dont get full of "division by 0" errors.

Explanation:

"puts" first argument is the device to output argument two. There are three pre-defined devices:

0 is STDIN, 1 is STDOUT, and 2 is STDERR

After decreasing i (with i-=1) once, on the second cycle we will get

Wrong file mode for attempted operation

which is the exception/error.

P. Ktinos

Posted 2016-12-23T21:45:59.430

Reputation: 2 742

1

Swift, 22 bytes

for i in 0...1{[0][i]}

Pretty self-explanatory, crashes with sigill on second iteration. You can do the exact same thing in Python with 2 less bytes, but I really wanted to do a Swift submission.

Try it online!

osuka_

Posted 2016-12-23T21:45:59.430

Reputation: 391

1

Clojure, 21 bytes

Quite odd challenge, I hope I understood this correctly. On first iteration i is the + function which can be called with zero arguments and it returns zero, on second iteration (0) is evaluated and you get ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn.

(loop[i +](recur(i)))

Confirmation that loop is executed twice:

(loop[i +](do(print{:i i})(recur(i))))
{:i #object[clojure.core$_PLUS_ 0x7e72f43f clojure.core$_PLUS_@7e72f43f]}
{:i 0}

NikoNyrh

Posted 2016-12-23T21:45:59.430

Reputation: 2 361

@Carcigenicate what do you think? – NikoNyrh – 2017-01-11T01:07:33.120

1

Dart, 20 bytes

_ i=1;for(;;)0~/i--;

Since Dart discards static type information at runtime, declaring a variable with an unknown type ( _ ) gives a warning but doesn't stop the code from running. Then we just trigger an exception by doing integer divide by 0.

Bonus 1, 23 bytes

_ x;for(;;)x=x?.a??"x";

Same thing as above, but it doesn't utilize a floating point exception. It uses the "null operator" on x to access member a, which evaluates to null when x is null and throws a runtime error when x is not null but doesn't have the property x. We also use the "??" operator to coerce the null value from x?.a to "x". Strings don't have a property named "a", so it errors.

Bonus 2, 22 bytes

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

This declares an anonymous function that returns void, which actually return null (since everything is nullable in Dart). The first loop iteration gets a successful call and sets x to null. The second loop iteration errors because the Null type doesn't have a call method.

Edit: To clarify, the warning given above is not from Dart but from Dart's analyzer (so its a pre-runtime warning).

Dwayne Slater

Posted 2016-12-23T21:45:59.430

Reputation: 111

1

SmileBASIC, 15 bytes

EXEC.>SPSET(0)W

12Me21

Posted 2016-12-23T21:45:59.430

Reputation: 6 110

1

C#, 23 bytes

Out of range (23 bytes):

()=>{while(""[1]>'a');}

Divide by zero (25 bytes):

()=>{for(int i=0;;i/=i);}

Runtime binder exception (33 bytes):

()=>{for(;;){dynamic d=1;d.D();}}

Null reference (36 bytes):

()=>{string x=null;while(x[1]>'a');}

Stackoverflow (C# 7 local function) (37 bytes):

()=>{while(true){bool b()=>b();b();}}

Argument exception (48 bytes):

()=>{while(System.IO.File.ReadAllText("")=="");}

Invalid operation (77 bytes):

()=>{var v=new System.Collections.Generic.List<int>{1};v.ForEach(V=>v[0]=0);}

Metoniem

Posted 2016-12-23T21:45:59.430

Reputation: 387

1

HQ9+-, 2 bytes

Q-

The program consists of two parts:

  • Q- Prints out the source code (which, in this case, is Q-).
  • - Behavior changes based on the previous character(s) in the program. Since Q came before -, the program enters into a recursive loop and finally quits, raising the error:

[1] 1979 segmentation fault ./hq9+-i test.hq9

Left SE On 10_6_19

Posted 2016-12-23T21:45:59.430

Reputation: 111

1

Underload, 13 bytes

(!a(:^)*^)::^

Try it online!

Stack trace:

(...)   | (!a(:^)*^)
:       | (!a(:^)*^)(!a(:^)*^)
:       | (!a(:^)*^)(!a(:^)*^)(!a(:^)*^)
^       | (!a(:^)*^)(!a(:^)*^)
 !      | (!a(:^)*^)
 a      | ((!a(:^)*^))
 (...)  | ((!a(:^)*^))(:^)
 *      | ((!a(:^)*^):^)
 ^      |
  (...) | (!a(:^)*^)
  :     | (!a(:^)*^)(!a(:^)*^)
  ^     | (!a(:^)*^)
   !    |
   a    | <error>

Underload is interesting. The only way to loop is to create a sort of quine. The basic idea is this:

  • Push a block containing the loop body to the stack: (...)
  • Duplicate it, and then execute it. This means the loop body will be run with the loop body string at the bottom of the stack: (...):^
  • In the loop body, immediately "uneval" with the a command: (a...):^
  • Append :^ to the end: (a(:^)*...):^. This recovers the original program (and in fact, if we output right here, we would have a quine.)
  • Execute this stack value to loop: (a(:^)*^):^. This is the basic structure of our loop program.

I've made a few changes to this idea. The first is that we duplicate twice rather than once before entering the loop. Normally, this would not be significant (as we would just have an unused value at the bottom of the stack) but I also add a ! (delete) at the beginning of the loop body, which means that the stack will be gradually "worn down." After two iterations of the loop, the stack is empty, so running a causes a segfault in the TIO interpreter.

This shouldn't violate rule 6, because any competent Underload interpreter would do TCO.

Esolanging Fruit

Posted 2016-12-23T21:45:59.430

Reputation: 13 542

1

REXX, 14 bytes

do i=0
  i=j
  end

This creates an infinite for-loop with i as a counter, but during the loop, i is reassigned from 0 to j, which, as an unassigned symbol, contains the string J.

The result:

     1 +++ do i=0
Error 41 running "test.rexx", line 1: Bad arithmetic conversion
[Finished in 0.1s with exit code 215]

Another option is to drop i, but that is three bytes longer.

idrougge

Posted 2016-12-23T21:45:59.430

Reputation: 641

1

Whitespace, 16 bytes

[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][T   N
S T _Print_top_as_integer][N
S N
N
_Jump_to_Label_LOOP]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Probably my shortest Whitespace answer thus far. :)

Explanation in pseudo-code:

Push 0 to the top of the stack
Start LOOP:
  Pop and print the top of the stack as integer to STDOUT
  Go to next iteration of LOOP

Run process

Command    Explanation             Stack    STDOUT    STDERR

SSSN       Push 0                  [0]
NSSN       Create Label_LOOP       [0]
 TNST      Print top as integer    []       0
 NSNN      Jump to Label_LOOP      []

 TNST      Print top as integer    []                 Error: Can't do OutputNum

Stops with an error because it tries to output the top of the stack, which isn't there anymore.

Kevin Cruijssen

Posted 2016-12-23T21:45:59.430

Reputation: 67 575

1

HadesLang, 34 bytes

func o[]
while[true]
o: //Recursive call to o
end
end
o: //Call o the first time

This just calls itself infinitely, resulting in a System.StackOverflowExceptionafter ~300ms.

Azeros

Posted 2016-12-23T21:45:59.430

Reputation: 41

1

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.

GammaFunction

Posted 2016-12-23T21:45:59.430

Reputation: 2 838

1

Deadfish~, 5 bytes

{isc}

Try it online!

This tries to follow the instructions "increment, square, print as a character" 10 times. As soon as a value greater than 255 is reached (which is 676 on the fourth iteration), it crashes trying to print a character value that does not exist.

Reinstate Monica

Posted 2016-12-23T21:45:59.430

Reputation: 1 382

1

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

Shaun Bebbers

Posted 2016-12-23T21:45:59.430

Reputation: 1 814

1

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!

gggg

Posted 2016-12-23T21:45:59.430

Reputation: 1 715

1

Java, 26 bytes

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

v->{for(var a=".";;a+=a);}

Benjamin Urquhart

Posted 2016-12-23T21:45:59.430

Reputation: 1 262

1

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.

user85052

Posted 2016-12-23T21:45:59.430

Reputation:

0

BrainFuck (4 bytes)

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

user181782

Posted 2016-12-23T21:45:59.430

Reputation: 1

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 – 2016-12-24T00:43:36.397

3

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 – 2016-12-24T01:20:55.123

Why 3 bytes? +[>+] works fine on most interpreters without infinite memory and is only 1 byte extra. – FinW – 2016-12-24T10:31:28.437

1@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 – 2016-12-24T12:55:20.720

Underflowing, then? - is enough. That makes it 4 bytes too. – Asu – 2016-12-27T22:50:45.100

0

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?

Mega Man

Posted 2016-12-23T21:45:59.430

Reputation: 1 379

0

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

BATMAN

Posted 2016-12-23T21:45:59.430

Reputation: 1

2I'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 – 2016-12-26T23:00:03.190

0

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

cookie

Posted 2016-12-23T21:45:59.430

Reputation: 271

0

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.

Patrick Roberts

Posted 2016-12-23T21:45:59.430

Reputation: 2 475

3That costs ¥5? :( – Esolanging Fruit – 2017-03-16T06:25:15.743

0

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

77Tigers

Posted 2016-12-23T21:45:59.430

Reputation: 11

"Recursion without Tail Call Optimization is invalid" – ASCII-only – 2018-06-01T10:59:04.003

Sorry, forgot about that. – 77Tigers – 2018-06-01T11:24:19.023

0

k, 4 chars

,:\0

Will terminate after a few seconds with SEGV

skeevey

Posted 2016-12-23T21:45:59.430

Reputation: 4 139

-2

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

sonrad10

Posted 2016-12-23T21:45:59.430

Reputation: 535

How is this any different to my answer??

– FlipTack – 2016-12-24T00:32:33.093

@Flp.Tkc I hadn't realised that someone had already posted this answer. But yes, we have taken the same approach to this. – sonrad10 – 2016-12-24T00:34:33.950

Seeing that you've already realized that the aproach is the same, you should either reverte the answer or delete it. – Ismael Miguel – 2016-12-24T04:43:04.870

2

@Flp.Tkc Duplicate answers are allowed

– Martin Ender – 2016-12-24T09:36:00.473

@IsmaelMiguel cc ^ – Martin Ender – 2016-12-24T09:36:16.727

3@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 – 2016-12-24T17:27:29.843

sonrad10's slightly different answer from FlipTack's was important for me in Perl 5: (FlipTack) x/x$x/$x, 5 bytes vs. (sonrad10) 0/i0/$i, 4 bytes. I hadn't realized yet I could just use a literal integer!

– g4v3 – 2016-12-27T21:58:56.303

@g4v3 it's still just a trivial, 1-char modification. – FlipTack – 2016-12-28T12:27:05.617

He didn't reach this code by reading yours, so I don't think it deserves downvotes. – mbomb007 – 2017-02-03T19:53:46.983