Why isn't it ending?

95

20

Your task: To write a program that should obviously terminate, but it never (to the extent of a computer crash) does. Make it look like it should perform a simple task: adding numbers, printing something,... But it just gets caught in an infinite loop.

Try to make your program very clear and simple, while it actually will get stuck in an unforeseen loop. Voters: judge the answers on how "underhanded" they are!

This is a popularity contest: Be creative!

Number9

Posted 2014-03-16T02:59:32.170

Reputation: 1 157

Question was closed 2016-04-15T16:22:17.707

1

I'm voting to close this question as off-topic because underhanded challenges are no-longer on-topic here. http://meta.codegolf.stackexchange.com/a/8326/20469

– cat – 2016-04-15T14:20:02.717

6Could someone please explain what I can do to make the question less broad? I am new here. Thank you! – Number9 – 2014-03-16T13:58:53.563

6This is just going to be a big list of typos and beginner's mistakes which cause loops. – Bill Woodger – 2014-03-17T00:51:25.707

Interesting question, but I haven't seen any truly creative answers yet. I promise up votes to anyone who doesn't use loops or obvious recursion! – ApproachingDarknessFish – 2014-03-17T05:35:03.107

@ValekHalfHeart Does my answer qualify? ;) There is a loop... but I wouldn't call the bug obvious. – Legat – 2014-03-17T14:31:30.730

@ValekHalfHeart No loops, no recursions: http://codegolf.stackexchange.com/a/24391/14901.

– VisioN – 2014-03-17T16:27:23.993

14I don't know if this counts, but my Microsoft Office is behaving exactly like this at the moment. – Level River St – 2014-03-22T11:40:53.417

You have just described every FORTRAN program I have look at. – ja72 – 2014-03-26T20:21:02.393

Did anybody see the PostScript answer? It does not use floating-point precision, but self-mutilating code. – luser droog – 2014-04-28T05:02:36.563

I feel like I've done this so many times by accident in Awk and now I can't think of a way to make it happen on purpose. – shadowtalker – 2014-08-09T12:22:31.103

Answers

185

Javascript

var x=prompt('Enter a value under 100');
while (x != 100) {
  x=x+1;
}
console.log('End!');

prompt() returns a string and the loop appends the character '1', it will never be equal to 100.

Michael M.

Posted 2014-03-16T02:59:32.170

Reputation: 12 173

Can someone please provide explanation Or some pointers for why this never terminates ? – Sankalp – 2015-02-06T03:54:55.707

1@Sankalp, the + operator here is the string concatenation, not the addition. – Michael M. – 2015-02-07T09:48:18.777

13You got me with that one… the (actually) higher-voted examples are all just abusing syntax… but that one is nice! – bwoebi – 2014-03-17T17:37:13.310

4Chrome on Kubuntu became unresponsive, hang everything and I had to hard reset :) – Sergey Telshevsky – 2014-03-19T10:08:19.163

Similar should work on Python too – Sergey Telshevsky – 2014-03-19T10:16:09.107

@Vlakarados, sorry about that :) you can also probably looking for the pid of the chrome tab with the most CPU usage and kill it. – Michael M. – 2014-03-19T10:24:44.353

Terminal hanged up as everything else, that's strange as IIRC on Win they didn't hang the system completely :) Anyway, nice one – Sergey Telshevsky – 2014-03-19T10:58:27.803

is x considered a string so 1 is converted to a string and it's using concatenation? – Cruncher – 2014-03-19T17:57:16.070

@Cruncher, absolutly. – Michael M. – 2014-03-19T18:11:00.617

@Michael oops. Didn't see the spoiler section. It really blends in on my browser – Cruncher – 2014-03-19T18:31:21.340

4@Vlakarados: Python won't do the implicit type conversion Javascript does. On Python, the equivalent code using raw_input or Python 3 input raises a TypeError. – user2357112 supports Monica – 2014-03-20T04:52:23.107

@user2357112 right, I thought about it the other way around - in Python + is a concatenation operator too. Thanks for pointing out – Sergey Telshevsky – 2014-03-20T06:54:51.100

2There is not check on the fact that value is actually under 100 so it stops normally when you enter "100" :'-( – C.Champagne – 2014-03-21T17:18:45.970

@C.Champagne instead of != you could use !== to prevent the loop from terminating when you enter 100. – starbeamrainbowlabs – 2014-07-23T11:45:25.753

87

C

Just a basic example program that illustrates the three different kinds of while-loops in C.

int main() {

    int x = 0;

    // Multi-statement while loops are of the form "while (condition) do { ... }" and
    // are used to execute multiple statements per loop; this is the most common form
    while (x < 10) do {
        x++;
    }

    // x is now 10

    // Null-statement while loops are of the form "while (condition) ;" and are used
    // when the expression's side effect (here, decrementing x) is all that is needed
    while (x-- > 0)
        ; // null statement

    // x is now -1

    // Single-statement while loops are of the form "while (condition) statement;"
    // and are used as a shorthand form when only a single statement is needed
    while (x > -10)
        x--;

    // x is now -10

    return 0;
}

While loops don't have a "do" before the opening curly brace. This actually creates a do-while loop inside of the (x < 10) loop that's terminated by the following "null statement" while loop. Since x is incremented inside of the loop and then decremented in the do-while loop's condition, the inner loop never terminates, and so neither does the outer loop. The "single-statement" loop at the end is never reached.

If you're still confused, look here (externally hosted because codegolf.SE doesn't like code blocks in spoilers).

Fraxtil

Posted 2014-03-16T02:59:32.170

Reputation: 2 495

8Haha, I figured this one out before looking at the solution spoiler. :P – Joe Z. – 2014-03-17T14:29:13.900

54Why did you pass up such an excellent opportunity to use the "goes to" operator? (x --> 0) – corsiKa – 2014-03-17T16:57:51.170

2Oh wow. This is wonderfully evil. Took me four reads through to find it. – Patrick M – 2014-03-19T08:55:18.350

This took me forever to figure out, but only because I read the comments. – MirroredFate – 2014-03-21T00:22:42.340

1@JoeZ. Way too easy. The most upvoted solution was better. That one I didn't find. – Anonymous Pi – 2014-03-21T01:59:29.960

It's only easy if you're well-versed in C. Any answer on this post could be declared "too easy" by someone familiar enough with the language. – Fraxtil – 2014-03-21T02:51:27.473

@Fraxtil Actually, it's easy if you know C, C++, Java, etc. I have no experience whatsoever with C, but I still figured this out within fifteen seconds. – The Guy with The Hat – 2014-03-21T13:25:40.297

3

@Hat Guy, Bash has the for;do and while;do syntax so I can see people getting thrown off by this, even if they're familiar with non-C/C++ languages. http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html

– nemec – 2014-03-22T02:28:41.117

85

JavaScript

var a = true;
(function() {
  while(!a){}
  alert("infinite");
  var a = true;
})();

Variable hoisting: JavaScript will actually grab my second definition of var a = true;, declare it at the top of the function as var a;, and modify my assignment to a = true; meaning a will be undefined at the time it enters the while loop.

Newbrict

Posted 2014-03-16T02:59:32.170

Reputation: 971

3Could you add a better explanation of why this never terminates? Please go into depth about "variable hoisting" :) – Number9 – 2014-03-16T22:32:45.857

1@Number9 I hope that helps, google has much better examples than this ;) – Newbrict – 2014-03-16T22:39:33.420

25Holy shit this is even worse than semicolon insertion. +1! – tomsmeding – 2014-03-17T12:03:05.713

2Only trouble I see with this program is that it doesn't look like it performs a simple task... it looks like it should essentially do nothing. Maybe add an alert after the loop. – PeterT – 2014-03-17T16:19:17.123

@PeterT thanks, I just tested to make sure it hung my browser, I've added your suggestion. – Newbrict – 2014-03-17T16:22:35.063

For anyone interested: I found a good article on JavaScript scoping and hosting which goes into deeper depth: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

– ComFreek – 2014-03-17T18:22:08.223

2You should change a = 1 to a = true. The code will still have the infinite loop that way, but it will be clearer that the reason is not some quirk in JavaScript conversion from ints to booleans. – Rory O'Kane – 2014-03-22T21:53:22.070

49

C#

class Program
{
    // Expected output:
    // 20l
    // 402
    // 804
    // l608
    // 32l6
    // game over man

    static void Main()
    {
        var x = 20l;
        while (x != 6432)
        {
            Console.WriteLine(x);
            x *= 2;
        }
        Console.WriteLine("game over man");
    }
}

The number literal in the first line of the function is not a '201', but a '20' with a lowercase 'L' (long datatype) suffix. The number will overflow pretty quickly without ever hitting 6432, but the program will keep going unless overflow checking was switched on in the build options.
Sensibly, Visual Studio 2013 (and probably other versions too) gives you a warning for this code, recommending that you use 'L' instead of 'l'.

BenM

Posted 2014-03-16T02:59:32.170

Reputation: 1 409

@AnonymousPi This is kind of different because the characters are actually not identical. Eta versus H is a different story though. – NoOneIsHere – 2016-03-02T15:28:46.320

12Oh, the l is supposed to look like a 1! I'm stupid. :\ – Joe Z. – 2014-03-17T14:27:07.757

6Suggestion for improvement: replace the 1s in the expected output section with ls as well (it's easier to spot the weird character when you have real 1s to compare against) – Allen Gould – 2014-03-17T16:09:33.960

The expected output comment is misleading part – Newbrict – 2014-03-17T16:38:14.470

I don't know if it's the retina display or the font, but we can easily distinguish the l on my macbook : http://imgur.com/K0UsPf6

– Michael M. – 2014-03-17T17:32:25.223

3

Yeah, it does seem to be quite environment-specific. @Michael's font looks very different to the font on my home computer (http://imgur.com/PKIuJpr - Chrome, Windows 8), and the trick seems to work better on my work computer than my home computer, even though they've got quite similar specs. My phone's browser doesn't seem to show code in a fixed-pitched font, and the trick doesn't work at all on it.

– BenM – 2014-03-17T18:41:22.997

@AllenGould: I considered that, but I thought it might ruin the trick if all the 1s looked odd. The single l might have a better chance of slipping by unnoticed. Maybe it would be better to tinker with the code so that there aren't any 1s in the expected output at all. – BenM – 2014-03-17T20:14:35.300

1

FTR, here's what it looks like on my work computer (http://imgur.com/Opfs3BH - Firefox, Windows 7). I reckon that one could even fool quite astute people.

– BenM – 2014-03-17T20:21:53.233

@BenM I was thinking the opposite - if all the 1s in the code are l, you don't have anything to compare against. :) – Allen Gould – 2014-03-17T20:51:18.917

15WHY DO PEOPLE KEEP ABUSING OF CHARACTERS THAT LOOK THE SAME? – Anonymous Pi – 2014-03-21T02:01:14.837

39

C

How about precision ?

int main(void)
{
    double x = 0;
    while(x != 10) x += 0.1;
    return 0;
}

Imagine you have to store a range of integer numbers <0;3> in computer memory. There are only 4 integer numbers in this range (0,1,2,3). It's enough to use 2 bits to store that in memory. Now imagine you have to store a range of floating point numbers <0;3>. The problem is there is an infinite number of floating point numbers in this range. How to store infinite number of numbers ? It is impossible. We can only store finite number of numbers. This is why some numbers like 0.1 are actually different. In case of 0.1 it is 0.100000000000000006. It is highly recommended to not use == or != in conditions as far as you use floating point numbers.

Scony

Posted 2014-03-16T02:59:32.170

Reputation: 501

1How does this work? – Mhmd – 2014-03-17T17:46:54.407

5Rounding errors. 0.1 is actually 0.100000000000000006 because 0.1 in binary is like 1/3 in decimal - it's binary expansion is infinite&periodic. – orion – 2014-03-17T18:32:06.220

3Not really a rounding error. Floating point values are approximate representations of a number. Performing exact comparisons between approximate values isn't going to work. – AKHolland – 2014-03-18T19:36:29.007

4This is why you (almost) never should compare float/doubles for equality. – Emanuel Landeholm – 2014-03-19T05:41:39.470

1I was waiting to see this one. Nice. – David Conrad – 2014-03-19T17:40:46.587

1I'll mention that a compiler is totally allowed to optimise this into int main() {}. – R. Martinho Fernandes – 2014-03-25T14:31:11.773

@R.MartinhoFernandes Don't think so, since it's an infinite loop, and the compiler can see that. Suppose the compiler can't just go removing an infinite loop there, can it? – tomsmeding – 2014-08-10T07:34:36.753

1@tomsmeding The compiler can assume that a program will eventually do some sort of I/O, volatile access, or terminate. This one clearly does none of the first two, so it "obviously" terminates. I.e. the important thing that the compiler can see here is that the loop does no observable work, not that it is infinite. – R. Martinho Fernandes – 2014-08-10T14:48:08.857

33

HTML / JavaScript

Imagine you have an input box in your page:

<input onfocus="if (this.value === '') alert('Input is empty!');">

And now you want to type something in it... Try in Chrome: http://jsfiddle.net/jZp4X/.

Standard browser dialog box called with alert function is modal, so when it's displayed it takes the focus out of the text box, but when it is dismissed the text box receives the focus back.

VisioN

Posted 2014-03-16T02:59:32.170

Reputation: 4 490

Aw it doesnt work for me nice try tho :P EDIT: I used Google Chrome 42.0.2311.90 – YoYoYonnY – 2015-05-01T20:47:58.647

It works on Chrome for me – Oliver Ni – 2015-07-29T02:43:48.947

Doesn't work for me, and gives me the option to "Prevent page from displaying additional dialogs". – NoOneIsHere – 2016-03-02T15:31:20.367

It also works in Safari (which can't be closed at all), but I can't test now how it behaves in other browsers. – VisioN – 2014-03-17T14:02:49.650

5in firefox, the input doesn't have autofocus on alert close, and from the second time it offers me to not show more alerts and then I can write in the textbox normally – Einacio – 2014-03-17T16:20:23.123

@Einacio I have just tested it in Opera -- the same spamming effect as in Chrome and Safari. Shame about FF. Is it the only one with the resistance? How about IE? BTW, option to stop spamming with alert dialogs I consider as Ctrl+C in console. – VisioN – 2014-03-17T16:25:18.927

6Nice one. +1 for no loops or recursion. – ApproachingDarknessFish – 2014-03-17T17:11:47.880

I face the same problems as Einacio with Chrome 33 and IE 11. – ComFreek – 2014-03-17T19:59:13.803

5No loops in either Firefox or Chrome. FF shows the alert once when the dialog is clicked, you dismiss it and that's the end of it. Can click it again to repeat. Chrome does the same, but leaves the box focused, and you can even type in it. Sorry, maybe on older versions this was a problem, but not anymore. – RomanSt – 2014-03-18T13:03:46.570

@romkyns It works as expected on my newest Chrome 33.0.1750.152 on Mac, in Safari 7.0.2 and in Opera 20.0.1387.77. As you may see all the versions are up to date. Maybe the issue is in operating system? – VisioN – 2014-03-18T13:11:33.817

6IE11 works exactly the same as Chrome for me. I think you've inadvertently found an example of something that works one way on every modern browser on Mac, and a different way on every modern browser on Windows! – RomanSt – 2014-03-18T13:18:03.800

ValekHalfHeart: Actually this is a loop. Commonly called event loop. :p – Max Ried – 2014-03-20T11:28:09.090

1Works normally (no loops) on MSIE11 – kinokijuf – 2014-03-22T10:10:08.460

32

C++

#include <iostream>
#include <cstddef>

int main() {
    size_t sum = 0;
    for (size_t i = 10; i >= 0; --i) {
         sum += i;
    }
    std::cout << sum << std::endl;
    return 0;
}

The condition i >=0 is always true because size_t is unsigned.

FDinoff

Posted 2014-03-16T02:59:32.170

Reputation: 584

2Nice one, but compilers normally output a warning for this ;) – Synxis – 2014-03-17T13:43:15.963

2@Synxis Yes compilers do. But only if you turn on compiler warnings. g++ won't warn you about this without them. – FDinoff – 2014-03-17T13:47:16.727

5You should always use -Wall --pedantic anyway. – Martin Ueding – 2014-03-17T14:54:27.463

3@queueoverflow The warning doesn't show with only those flags. You need -Wsign-compare which can be turned on with -Wextra. – FDinoff – 2014-03-17T15:04:07.660

@FDinoff I'm fairly sure clang will tell you even without explicitly using -Wall – miguel.martin – 2014-03-19T11:13:16.243

7One dash on -pedantic. #pedantic – David Conrad – 2014-03-19T17:39:58.643

You are not guaranteed to have a definition of size_t in scope after including iostream, much less that it is available at global scope. – celtschk – 2014-03-22T17:23:01.940

@celtschk I added #include <cstddef> is that better? – FDinoff – 2014-03-22T17:27:24.930

A bit. cstddef defines size_t in namespace std, and may (but is not required to) also put it into global scope. So you could do any of the following: (1) prefix each size_t with std:: (where it is guaranteed to be found), (2) include stddef.h instead (which is guaranteed to exist and to put size_t in global scope in addition to namespace std), or (3) forget good style and add using namespace std; :-) – celtschk – 2014-03-22T17:35:15.427

29

bash

(There was a request for no loops or recursion)

#!/bin/bash

# Demo arrays

foo=("Can I have an array?")

echo $foo

echo ${foo[0]}

foo[2] = `yes`

echo $foo

echo ${foo[2]}

Instead of assigning the string 'yes' to foo[2], this calls the system command yes, which fills up foo[2] with a never ending amount of "yes\n".

GreenAsJade

Posted 2014-03-16T02:59:32.170

Reputation: 333

Eventually runs bash out of memory and crashes it – Digital Trauma – 2014-03-17T18:14:41.663

4Yes, indeed it does. But a crash was kind of allowed by the question :) – GreenAsJade – 2014-03-17T21:55:44.497

Yes, just an observation :). Upvoted. – Digital Trauma – 2014-03-17T22:00:21.713

In fact, I reckon that programs in this little comp that actually crash your machine, or some other denial of service, should get bonus marks ) – GreenAsJade – 2014-03-21T01:16:18.270

Correction: yes is just a coreutils program. Not a syscall. – mniip – 2014-03-22T22:14:03.010

Reworded to avoid this technicality all together - I wasn't focused on the nature of yes, rather I was noting that it is not a bash string, it's a call to an utility outside bash accessed via the backtick command substitution. – GreenAsJade – 2014-03-22T23:46:23.287

Does that program have any purpose that can't be fulfilled by hard coding "yes" into your program? – Cole Johnson – 2014-06-16T00:49:28.883

What do you mean by "hard coding 'yes' into your program"? This program ostensibly (and actually) demonstrates how to use array syntax in bash. The string "yes" is just hardcoded, ostensibly, as is the string "Can I have an array". The fact that it's not actually hardcoded is the way this solution to the OP's challenge works. – GreenAsJade – 2014-06-16T02:46:16.607

28

C

Letter "x" was lost in a file. A program was written to find it:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  FILE* fp = fopen("desert_file", "r");
  char letter;
  char missing_letter = argv[1][0];

  int found = 0;
  printf("Searching file for missing letter %c...\n", missing_letter);
  while( (letter = fgetc(fp)) != EOF ) {
    if (letter == missing_letter) found = 1;
  }
  printf("Whole file searched.\n");
  fclose(fp);
  if (found) {
    printf("Hurray, letter lost in the file is finally found!\n");
  } else {
    printf("Haven't found missing letter...\n");
  }
}

It was compiled and to ran and it finally shout:

Hurray, letter lost in the file is finally found!

For many years letters have been rescued this way until the new guy came and optimized the code. He was familiar with datatypes and knew that it's better to use unsigned than signed for non-negative values as it has wider range and gives some protection against overflows. So he changed int into unsigned int. He also knew ascii well enough to know that they always have non-negative value. So he also changed char into unsigned char. He compiled the code and went home proud of the good job he did. The program looked like this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  FILE* fp = fopen("desert_file", "r");
  unsigned char letter;
  unsigned char missing_letter = argv[1][0];

  unsigned int found = 0;
  printf("Searching file for missing letter %c...\n", missing_letter);
  while( (letter = fgetc(fp)) != EOF ) {
    if (letter == missing_letter) found = 1;
  }
  printf("Whole file searched.\n");
  fclose(fp);
  if (found) {
    printf("Hurray, letter lost in the file is finally found!\n");
  } else {
    printf("Haven't found missing letter...\n");
  }
}

He came back to a havoc on the next day. Letter "a" was missing and even though it was supposed to be in the "desert_file" containing "abc" the program was searching for it forever printing out only:

Searching file for missing letter a...

They sacked the guy and rolled back to previous version remembering that one should never optimize datatypes in working code.

But what is the lesson they should have learnt here?

First of all, if you take a look at the ascii table you'll notice that there is no EOF. That's because EOF is not a character but a special value returned from fgetc(), which can either return character extended to int or -1 denoting end of file.
As long as we are using signed char everything works well - char equal to 50 is extended by fgetc() into int equal to 50 as well. Then we transform it back to char and still have 50. Same happens for -1 or any other output coming from fgetc().
But look what happens when we use unsigned char. We start with a char in fgetc() extend it to int and then want to have an unsigned char. The only problem is that we can't preserve -1 in unsigned char. Program is storing it as 255 which no longer equal to EOF.

Caveat
If you take a look at section 3.1.2.5 Types in copy of ANSI C documentation you'll find out that whether char is signed or not depends solely on implementation. So the guy probably shouldn't be sacked as he found a very tricky bug lurking in the code. It could come out when changing the compiler or moving to different architecture. I wonder who would be fired if the bug came out in such a case ;)

PS. Program was built around the bug mentioned in PC Assembly Language by Paul A. Carter

Legat

Posted 2014-03-16T02:59:32.170

Reputation: 541

1I love you. Feed me with your stories pls :( – YoYoYonnY – 2015-05-01T20:50:53.150

This is absolutely brilliant! – kirbyfan64sos – 2015-05-01T22:26:29.323

7I love that there's a story with the solution. – jpmc26 – 2014-03-22T01:55:11.107

Haha! I guess it's the only one. Thanks for reading through! – Legat – 2014-03-22T10:26:17.340

21

Regex

With appropriate input, the following regex can cause most backtracking regex engine to go into backtracking hell:

^\w+(\s*\w+)*$

Simple input such as "Programming Puzzles and Code Golf Stack Exchange - Mozilla Firefox" or "AVerySimpleInputWhichContainsAnInsignificantSentence." (both strings quoted for clarity) is enough to keep most backtracking regex engines running for a long time.

Since (\s*\w+)* allows for the expansion \w+\w+\w+...\w+, which means the regex engine will basically try out all possible ways to split up a string of word characters. This is the source of the backtracking hell.
It can easily be fixed by changing \s* to \s+, then (\s+\w+)* can only be expanded to \s+\w+\s+\w+...\s+\w+.

n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

Posted 2014-03-16T02:59:32.170

Reputation: 5 683

3I hate backtracking regex engines. – David Conrad – 2014-03-19T17:43:24.367

2I tried this with Perl first, but it appears that Perl can notice a loop here. I didn't try AWK, because no regular expression can cause such behavior in AWK. PHP automatically makes regular expression which takes too long to match fail (which is silly, but that's PHP for you - it automatically inserts bugs into programs). However, it actually works in Python. – Konrad Borowski – 2014-03-22T12:19:33.947

1

@xfix: As for why Perl managed to avoid backtracking hell, this article explains the reason. However, it is not enough against the case as shown here (scroll down to performance section). PHP (actually PCRE library) has a backtracking limit, and a proper program should always check for the return value of the function to decide whether the execution was halted, or ran to completion.

– n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-03-22T13:30:31.457

1This is so SLICK. – alvonellos – 2014-03-23T03:53:59.577

20

JavaScript

function thiswillLoop(){
var mynumber = 40;
while(mynumber == 40){
mynumber = 050;
}
return "test";
}
thiswillLoop();

050 is an octal constant in Javascript, and it happens to have the decimal value of 40.

wuiyang

Posted 2014-03-16T02:59:32.170

Reputation: 371

It is obvious.. – Oliver Ni – 2015-01-01T22:47:57.693

73I find this obvious. :-) – Justin – 2014-03-17T01:41:10.447

6I didn't know javascript did this. But after reading the code I said: "050 has to be some way of representing 40, probably base 8 or something" – Cruncher – 2014-03-19T18:24:06.897

This needs to be hidden better. – Paŭlo Ebermann – 2014-03-24T11:48:54.057

18

Haskell

head $ reverse $ (repeat '!') ++ "olleH"

Well, think of it! It would be the same as head $ "Hello" ++ (repeat '!'), i.e should just return 'H'.

In haskell lists are recursive structures, with first element being the topmost. To append to a list, you have to unroll all those elements, place your appendix, and put the lifted elements back. That wouldn't work on an infinite list. Similarly, reversing an infinite list won't magically give you your "Hello" back. It will just hang forever.

mniip

Posted 2014-03-16T02:59:32.170

Reputation: 9 396

1Too bad this doesn't actually work :-/ – John Dvorak – 2014-03-17T06:38:37.650

1How doesn't it work? – danmcardle – 2014-03-18T01:47:34.867

@crazedgremlin when I tested this on Fedora the OS eventually killed the process. (< 5 minutes) because it used up all the memory on the system. – FDinoff – 2014-03-18T14:00:09.400

Interesting! I didn't realize that this happened. I don't venture into gobbling-all-memory territory all that often. – danmcardle – 2014-03-18T16:07:25.217

4That's still a valid solution: it doesn't exit, it runs as long as it can till the system can't support it anymore... – GreenAsJade – 2014-03-19T01:18:15.610

16

Java under Windows

public class DoesntStop
{
    public static void main(String[]a) throws InterruptedException, IOException
    {
        ProcessBuilder p = new ProcessBuilder("cmd.exe","/c","dir");
        p.directory(new File("C:\\windows\\winsxs"));
        Process P = p.start();
        P.waitFor();
    }
}

Program relies on a jammed standard output stream from the commandline to get stuck. The WinSXS directory under windows has multiple thousands of files with long names so it is almost guaranteed to clog stdout, and the waitFor can't return so the program is deadlocked

masterX244

Posted 2014-03-16T02:59:32.170

Reputation: 3 942

1Maybe I'm being dense, but won't this return eventually? It just might take awhile. Maybe I don't get what you mean by "clog[ging] stdout". – asteri – 2014-03-17T17:15:03.160

4if the stream is not emptied the program blocks, caused me some headaches already thats why i used it; the long directory only ensures that the buffer runs full – masterX244 – 2014-03-17T17:21:21.480

Ah, gotcha. Nice! +1 – asteri – 2014-03-17T17:57:20.753

15

To compare apples and oranges... in C

I'm impressed that there is no piece of code here using a goto... (You know: Goto is evil!)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    char *oranges = "2";
    long int apples;

next_harvest:

    apples = random() % 3;

    printf("%ld apples comp. %s oranges ...\n", apples, oranges);

    if( apples != (long int)oranges )
    {
        sleep(1);
        goto next_harvest;
    }

    return 0;
}

The sleep is just for being able to read it. Press ^C if you don't have an endless amount of time to wait for something that never happens ;-)

max.haredoom

Posted 2014-03-16T02:59:32.170

Reputation: 369

9You sneaky bastard, goto is innocent in this :) – orion – 2014-03-17T10:36:07.090

is the random() the vodoo used? – masterX244 – 2014-03-17T15:47:20.817

@masterX244 No, it isn't. Take a close look at the cast here. What happens when you omit the cast? – hvd – 2014-03-17T15:50:17.103

1ahh, "2" !=2 ; got it – masterX244 – 2014-03-17T15:55:34.577

2Well "2" probably can't ever be 2, but if you used a bigger number (and a multiple of at least 4), it could happen ;) – orion – 2014-03-17T18:34:00.917

1@orion: Yes you are right, it could be. And goto is still evil, but bad type castings are even more evil! – max.haredoom – 2014-03-17T21:49:55.633

@hvd: If you omit the type casting you 'll get a warning from the compiler. Still the behaviour will be the same. – max.haredoom – 2014-03-17T21:53:31.317

@max.haredoom Yes, I know. That warning was a hint to masterX244 to understand what is happening. – hvd – 2014-03-17T22:43:39.123

12

C, with certain optimizing compilers

This program increments an integer variable until it overflows.

#include <stdio.h>
#include <stdint.h>
int main()
{
    int32_t x = 0;
    while(x + 1 > x)
        x++;
    printf("Got overflow!\n");
    return 0;
}

Signed integer overflow is undefined behaviour. Usually in practice it wraps, when optimizations are turned off. With optimizations on, compilers can and do decide that x + 1 > x is always true.

user253751

Posted 2014-03-16T02:59:32.170

Reputation: 818

Perhaps use int32_t; a 64 bit int would take really, really, really long (585 years if each iteration takes a nanosecond). – Paul Draper – 2014-03-25T02:55:46.847

11

C++

int main()
{
  int x = 1;
  //why doesn't this code terminate??/
  x = 0;
  while(x) {} //no-op/
  return 0;
}

The weird commenting style is the trick. Hint: trigraphs.

Doorknob

Posted 2014-03-16T02:59:32.170

Reputation: 68 138

This is a too basic example of an infinite loop. – Ismael Miguel – 2014-03-16T06:24:50.937

@Ismael But if x == 0, while (x) {} will never be entered... right? – Doorknob – 2014-03-16T06:50:09.257

Sorry, didn't see the x=0;. But looking at the code, won't it terminate right away? – Ismael Miguel – 2014-03-16T07:00:50.003

@Ismael Nope; look closely... – Doorknob – 2014-03-16T07:03:59.173

From what I see, it's still an infinite loop. – Ismael Miguel – 2014-03-16T07:24:41.353

Seems you have fooled a few people. I think I've got it, although I wasn't aware that comments in C worked like that. – w4etwetewtwet – 2014-03-16T09:48:30.610

??// == /* :) – TheDoctor – 2014-03-16T14:52:22.953

64Those Trigraphs are sooo overused here :( – TimWolla – 2014-03-16T20:29:34.033

75I almost feel like trigraphs should be put in Standard Loopholes Which Are No Longer Funny. – undergroundmonorail – 2014-03-16T21:41:26.180

6@TheDoctor: ??/ is a trigraph for a backslash character, so the backslash splices the line where x is assigned 0 to the end of the comment, making it part of the comment. – CasaDeRobison – 2014-03-16T22:43:16.630

4

@undergroundmonorail Posted

– Justin – 2014-03-17T02:45:56.347

Expanding trigraphs in comments is something I'll never understand why. – Cole Johnson – 2014-06-16T00:52:23.303

11

Java

I particular love this side effect of the autoboxing optimization:

class BoxingFun {
  public static void main( String[] args) {
    Integer max;
    Integer i;

    max = 100;
    for( i = 1; i != max; i++ ) {
      System.out.println("Not endless");  
    }
    max = 200;
    for( i = 1; i != max; i++ ) {
      System.out.println("Endless");  
    }
  }
}

Because of autoboxing, Integer objects behave almost like plain ints here, with one exception: The i != max in the for loops compares the references (identity) of the Integer objects, not their value (equality). For values up to 100 this surprisingly "works" nevertheless because of an optimization in the JVM: Java preallocates Integer objects for the "most common values" and reuses them when autoboxing. So for values up to 100 we have identity <==> equality.

Daniel

Posted 2014-03-16T02:59:32.170

Reputation: 231

5Given that some Java guys still consider C++ operator-overloading as evil ... – Daniel – 2014-03-23T09:01:54.427

You don't need the initialization = new Integer(0), as you are initializing the values afterwards anyways. (This might make the reason less obvious.) – Paŭlo Ebermann – 2014-03-24T10:19:22.677

@PaŭloEbermann: Good point, I have edited the code. – Daniel – 2014-03-24T10:26:40.930

9

Ruby/C

#include <stdio.h>
#ifdef llama
def int(*args)
end
def main(arg)
  yield
end
void = nil
#endif
#define do {
#define end }
int main(void) {
  int x = 10;
  while(x-=1) do
    printf("%i\n",x);
  end
    return 0;
}

This works correctly in C, counting down from 9 to 1 in STDOUT. When run in Ruby, it does not terminate, because

0 is not a false value in Ruby.

histocrat

Posted 2014-03-16T02:59:32.170

Reputation: 20 600

Do languages at once...impressive. – Paul Draper – 2014-03-25T02:57:06.617

7

JavaScript

// This multiplies the elements in the inner lists and sums the results.
function sum_of_products(var items)
{
        var total = 0;
        for(var i = 0; i < items.length; i++) {
                var subitems = items[i];
                var subtotal = 1;
                for(var i = 0; i < subitems.length; i++) {
                        subtotal *= subitems[i];
                }       
                total += subtotal;
        }
        return total;
}

// Should return 1*2 + 3*4*5 + 6*7*8*9 + 10*11 = 3196
sum_of_products([[1, 2], [3, 4, 5], [6, 7, 8, 9], [10, 11]]);

Both loops use the same loop variable, so depending on the input, the inner loop can keep the outer loop from ever finishing.

Aleksi Torhamo

Posted 2014-03-16T02:59:32.170

Reputation: 1 871

What language is this? – RononDex – 2014-03-17T10:11:03.490

@ronondex Javascript – tomsmeding – 2014-03-17T12:04:31.983

1Ah, yes, it's Javascript. I remembered to enable the syntax hilighting but had to forget to put it in the title too :) – Aleksi Torhamo – 2014-03-17T16:37:43.783

1I find this obvious. :-) – rafaelcastrocouto – 2014-03-20T12:43:54.377

@rafaelcastrocouto Yeah, it kind of is, but it's also really easy to miss, for example when moving a loop from one function to another or just glancing over code. Also, do note that this actually works correctly in some languages, including C, due to variable shadowing. :) – Aleksi Torhamo – 2014-03-20T17:57:44.887

7

Python

a = True
m = 0
while a:
    m = m + 1
    print(m)
    if m == 10:
        exit

it should be exit() and not exit. As I understand it, exit() is the command to exit the python interpreter. In this case the call is to the representation of the function and not to the function see: exit-discussion. Alternatively break would be a better choice.

Willem

Posted 2014-03-16T02:59:32.170

Reputation: 1 528

Could you please explain what exit actually is? It seems to be a class, but what is it used for? You could also change print m to print(m) so that this also works with Python 3. – Martin Thoma – 2014-03-17T17:54:17.010

1Those kinds of things... Like when my elseif didn't work because it was elif. – Anonymous Pi – 2014-03-17T18:04:45.813

Thanks @moose updated print statement and the spoiler message – Willem – 2014-03-17T19:10:08.490

7

C

This should print a code table for all ASCII characters, from 0 to 255. A char is large enough to iterate over them.

#include <stdio.h>

int main(){
    char i;
    for(i = 0; i < 256; i++){
        printf("%3d 0x%2x: %c\n", i, i, i);
    }
    return 0;
}

All chars are less than 256. 255++ gives 0 due to overflow, so the condition i < 256 always hold. Some compilers warn about it, some don't.

Rafał Cieślak

Posted 2014-03-16T02:59:32.170

Reputation: 171

To make is seem to do something more useful, maybe use something like printf("%3d %2x: %c", i, i, i); (for a code table) in your loop. – Paŭlo Ebermann – 2014-03-24T11:19:29.230

@PaŭloEbermann: Great idea. – Rafał Cieślak – 2014-03-24T18:27:20.927

I use this trick in my classroom, with printable unsigned characters between 32 and 128. :) – cpri – 2014-06-04T13:42:32.673

6

C++

How about the classical C++-programmer's trap?

int main()
{
   bool keepGoing = false;

   do {
       std::cout << "Hello, world!\n";
   } while( keepGoing = true );

   return 0;
}

CompuChip

Posted 2014-03-16T02:59:32.170

Reputation: 439

I don't get this? Is it about using. =instead of == ? – Mhmd – 2014-03-17T17:53:01.537

@user689 exactly. keepGoing = true was meant to compare the value of keepGoing, instead it assigns the value to keepGoing; in addition the whole statement keepGoing = true evaluates to true (which is what allows you to write things like a=b=c=d=0) leading to an infinite loop. – CompuChip – 2014-03-17T18:43:13.217

3This is ever more reason to use yoda conditions. – Ryan – 2014-03-20T03:51:37.460

@RyanEdwardDougherty Haha like that I never heard them being called. For the morning laugh thanks. – CompuChip – 2014-03-20T07:53:45.030

@RyanEdwardDougherty: Of course == true (or Yoda-style true ==) is redundant anyway, and the condition should simply read while (keepGoing). – celtschk – 2014-03-23T19:03:39.437

@Ryan No. Big no. This is reason to turn on compiler warnings. – R. Martinho Fernandes – 2014-03-25T14:40:38.123

6

Java:

public class LoopBugThing{
   public static void main(String[] args)
   {
      int i = 0;
      while(i < 10)
      {
         //do stuff here
         i = i++;
      }
      System.out.println("Done!");
   }
}

The "i = i++" is a pretty common beginner mistake and can be surprisingly hard to find

Richo

Posted 2014-03-16T02:59:32.170

Reputation: 161

6

Javascript

var а = 0;
a = 1;
while(а<10){
    a++;
}

The variables used in 1st and 3rd line are different from the ones used in 2nd and 3rd line.
One uses a (U+0061) while the other uses а (U+0430)

Clyde Lobo

Posted 2014-03-16T02:59:32.170

Reputation: 1 395

Just to hide it completely (replace á with U+0430) If this was your code, good luck finding the problem: var a;var points = 0;function fiftyfifty() {points++;if (Math.random() > 0.5)return true;}; á = fiftyfifty(); while (a === undefined) {á = fiftyfifty();} console.log("Points: " + points); I would give up, delete this forever, clean my computer, maybe virus scanner just to be sure and rewrite it completely. EDIT: Because var a = 0; a = 1; is not very realistic – YoYoYonnY – 2015-05-01T22:00:38.763

I don't see a problem here. I ran it and it worked fine. What am I missing? – Andrew Shepherd – 2014-03-19T00:19:46.747

this will most likely work everywhere since the unicode will probably be converted. Got a +1 since it is the most invisible as you can get! – rafaelcastrocouto – 2014-03-20T19:10:29.867

5

Haskell

Some code to time the computation of a given value of the Ackermann function. For very low values it usually terminates. On my machine very low values means something like 3 5 or smaller with compiled code and -O. In ghci low values means something like 3 3.

The ' symbol seems to mess up syntax highlighting, not sure why. In some places they are needed so can't remove all of them.

Edit- changed language.

{-# LANGUAGE NamedFieldPuns #-}
import Control.Concurrent.STM
import Control.Concurrent
import Data.Time.Clock.POSIX

data D = D { time :: !POSIXTime
           , m :: !Integer
           , n :: !Integer
           , res :: !(Maybe Integer)
           } deriving Show

startvalue = D 0 3 8 Nothing

-- increment time in D. I belive lensen make code like
-- this prettier, but opted out.
inctime t t' (d@D{time}) = d {time = time + t' - t }

-- Counting time
countTime :: TVar D -> POSIXTime -> IO ()
countTime var t = do
    t' <- getPOSIXTime
    atomically $ modifyTVar' var (inctime t t')
    countTime var t'

-- Ackermann function
ack m n
    | m == 0    = n + 1
    | n == 0    = ack (m - 1) 1
    | otherwise = ack (m - 1) (ack m (n - 1))

-- Ackerman function lifted to the D data type and strict
ack' (d@D{m, n}) = let a = ack m n
                   in seq a (d { res = Just a })

-- fork a counting time thread, run the computation
-- and finally print the result.
main = do
    d <- atomically (newTVar startvalue)
    forkIO (getPOSIXTime >>= countTime d)
    atomically $ modifyTVar' d ack'
    (atomically $ readTVar d) >>= print

This causes a livelock. The counting thread repeatedly causes the Ackermann computation to roll back since they touch the same TVar.

monocell

Posted 2014-03-16T02:59:32.170

Reputation: 2 551

marking it as lang-hs instead of lang-haskell seems to work better (it's one of the extensions in the google prettifier)

– Einacio – 2014-03-17T16:31:16.770

5

C++

A bit of random ?

class Randomizer
{
   private:
   int max;

   public:
   Randomizer(int m)
   {
      max = m;
      srand(time(NULL));
   }

   int rand()
   {
      return (rand() % max);
   }
};

int main()
{
  Randomizer r(42);
  for (int i = 0; i < 100; i++)
  {
     i += r.rand();
  }
  return (0);
}

Doesn't call the function rand but instead call recursively the Randomizer::rand function.

calimbak

Posted 2014-03-16T02:59:32.170

Reputation: 151

1This will eventually segfault, though. – kirbyfan64sos – 2015-05-01T22:31:24.563

5Extra parentheses in return statement, yuck. – David Conrad – 2014-03-19T17:48:03.450

5

Java -- No loops or recursion

I just started learning regular expressions and wrote my first program to test if my string matches a regular expression.

Unfortunately, the program does not produce any result. It holds up the terminal. Please help in finding the problem. I have not made any use of loops, there is no recursion involved. I am completely baffled.

import java.util.regex.*;

public class LearnRegex {
     public static void main(String[] args) {
         Pattern p = Pattern.compile("(x.|x.y?)+");
         String s = new String(new char[343]).replace("\0", "x");
         if (p.matcher(s).matches())
             System.out.println("Match successful!");
     }
}

What have I done wrong? Why doesn't my program end? Please help!

Ideone link here.

This is a stupid example of catastrophic backtracking. The complexity is O(2n/2). While the program might not run indefinitely, it'd probably outlive both living and non-living objects around and not-so-around.

devnull

Posted 2014-03-16T02:59:32.170

Reputation: 1 591

5

C

You should only need one of the two loops, but which one you need depends on your compiler.

main()
{
        int i, a[10];

        i = 0;
        while (i <= 10) {
            i++;
            a[i] = 10 - i;
            printf("i = %d\n", i);
        }

        /* Now do it in reverse */

        i = 10;
        while (i >= 0) {
            i--;
            a[i] = 10 - i;
            printf("i = %d\n", i);
        }

}

A simple bounds overrun that resets i to a non-terminating value. Compilers can differ on whether they allocate i above or below a on the stack, so I've included overruns in both directions.

alexis

Posted 2014-03-16T02:59:32.170

Reputation: 432

5

C / C++

C++ just allows the easy inline variable declarations used here, but it's just as easy to make this mistake in plain old C...

#include <stdio.h>

int main(void)
{
    int numbers[] = {2, 4, 8};

    /* Cube each item in the numbers array */
    for(int i = 0; i < 3; i++) {
      for(int j = 0; j < 3; i++) {
        numbers[j] *= numbers[j];
      }
    }

    /* Print them out */
    for(int i = 0; i < 3; i++) {
      printf("%d\n", numbers[i]);
    }

    return 0;
}

In the inner loop, 'j' is compared but never incremented. (The 'i++' should actually be 'j++'). This is not so much a sneaky trick but more of an actual error I've made in the past ;) Something to watch out for.

Dave Ceddia

Posted 2014-03-16T02:59:32.170

Reputation: 151

2This usually takes me at least 5 minutes to debug. I hate it when I did this. – user12205 – 2014-03-22T06:50:50.080

4

C#

The following is a simple class performing an arithmetic operation (summation) on a large input array using a background thread. A sample program is included.

However, even though it is quite straightforward, it never terminates. Note that there is no sleight of hand (character lookalikes, hidden/missing semicolons, trigraphs ;-), etc.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

class Program
{
    static void Main()
    {
        var summer = new BackgroundSummer(Enumerable.Range(1, 1234567));
        Console.WriteLine(summer.WaitAndGetResult());
    }
}

public class BackgroundSummer
{
    private IEnumerable<int> numbers;
    private long sum;
    private bool finished;

    public BackgroundSummer(IEnumerable<int> numbers)
    {
        this.numbers = numbers;
        new Thread(ComputingThread).Start();
    }

    public long WaitAndGetResult()
    {
        while (!finished) { /* wait until result available */ }
        return sum;
    }

    private void ComputingThread()
    {
        foreach(var num in numbers)
        {
            sum += num;
        }
        finished = true;
    }
}

This is an example of a real-world nasty bug which might appear in your code as well. Per the .NET memory model and C# specification, a loop such as the one in WaitAndGetResult might never terminate unless you specify the variable as volatile, because it is modified by another thread. See this StackOverflow question for details. The bug is dependent on the .NET implementation, so it might or might not affect you. But usually, running a release build on an x64 processor seems to display the problem. (I tried it with “csc.exe /o+ /debug- infinite.cs”.)

Mormegil

Posted 2014-03-16T02:59:32.170

Reputation: 1 148

4

Javascript

This once bit me years ago:

function outerloop(){
  for(i=0;i<10;i++){
    innerloop();
  }
}
function innerloop(){
  for(i=0;i<5;i++){
    console.log(i)
  }
}
outerloop();

The trick here is that when one uses for( i=0 ..., the variable i is created in the global scope (even if they're in separate functions), so it gets overwritten every time by the inner loop. This is an easy pitfall for those coming from C++ or PHP. The fix is to use var to declare the variable in local scope (for (var i...)

Manishearth

Posted 2014-03-16T02:59:32.170

Reputation: 709

4

PowerShell

$i = 1

do {
    $i++
} until( $i > 10 )

The > is not the greater-than operator (which is -gt); it is the redirection operator. Since nothing is returned, PowerShell evaluates the expression as false and continues.

Rynant

Posted 2014-03-16T02:59:32.170

Reputation: 2 353

3

It is a GUI program that will show an empty frame titled Hello, world! and hide the frame in 1 second.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Create a frame titled "Hello, world!".
                final JFrame frame = new JFrame("Hello, world!");
                frame.setVisible(true);

                // After 1 second...
                Timer timer = new Timer(1000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // Hide the frame.
                        frame.setVisible(false);
                    }
                });
                timer.setRepeats(false);
                timer.start();
            }
        });
    }
}

The frame is hidden, but it is not disposed, so the virtual machine would not terminate. Reference: http://docs.oracle.com/javase/7/docs/api/java/awt/doc-files/AWTThreadIssues.html#Autoshutdown

johnchen902

Posted 2014-03-16T02:59:32.170

Reputation: 1 177

5Anyone who has programmed in Swing enough will know this. – Justin – 2014-03-17T01:43:35.333

4@Quincunx I think your comment can be applied to all answer above. – johnchen902 – 2014-03-17T02:15:33.800

I agree. However, this answer is obvious to anyone who has barely begun programming in Swing. Swing programmers learn to use frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, and when that is forgotten, the application just doesn't close. This implies that something special is needed to close the frame, not just setting it as invisible. – Justin – 2014-03-17T02:23:41.097

Speaking as someone who's never heard of Swing before: Why would anyone who has been programming for more than a few weeks think that making something invisible is the same as releasing it? – alexis – 2014-03-23T18:34:50.290

@alexis I did, and I sometimes still forget to add setDefaultCloseOperation until I see my program is still running after closure. – johnchen902 – 2014-03-24T00:28:24.760

Fair enough, @johnchen, sorry if I came on too strong. IMHO Swing would make it easy to accidentally write non-terminating programs, but it's because it has a hidden event loop and you must explicitly arrange for termination instead of just letting your control flow run out as in most languages. Confusing visibility with resource (de)allocation is on another level-- I guess you have to know a little Swing before you can make this mistake. – alexis – 2014-03-24T09:03:41.680

3

C

int main(void) {
  float x = 0;
  while(x != 1) x+=0.1;
}

lots of nooses for a C developer....

bbozo

Posted 2014-03-16T02:59:32.170

Reputation: 167

main should be main() – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-03-17T09:18:22.530

1Also, this terminates perfectly. – trion – 2014-03-17T11:17:24.643

@trion, updated answer, should hang now – bbozo – 2014-03-17T12:24:00.427

2

It will hang on typical implementations, but for completeness: it will run successfully on implementations where FLT_RADIX is 10. A quick search brings up TIGCC as an example of such an implementation.

– hvd – 2014-03-17T15:17:44.640

1I imagine you could find another value that would be wonky when FLT_RADIX is 10, like 1.0/3.0. – David Conrad – 2014-03-19T18:01:41.317

@DavidConrad Indeed, but that cannot be expressed as a decimal literal. The 0.1 in this answer looks like it's probably an exact number, even though it's probably not. When you have to spell out the division operation, the problem becomes more obvious. – hvd – 2014-03-19T23:52:50.577

3

C

This was tested on a 64 bit machine with gcc using the compiler flag -fomit-frame-pointer.

int main() {
    long x = (long)main;
    asm("sub %0,%%rsp"::"i"(sizeof(x)));
}

This makes the return address the address of main. Which makes an infinite loop. The assembly line is needed to not run out of stack.

FDinoff

Posted 2014-03-16T02:59:32.170

Reputation: 584

Didn't get why it hangs until used -S with gcc. I took %0 as $0 and didn't understand why the asm line wasn't a nop. – Ruslan – 2014-03-19T09:15:21.457

3

Java

Spawns a thread that will sleep for 1 second. The program should effectively sleep for a second while waiting for that thread to quit, and then end.

import java.lang.*;

class A {
    static boolean done;
    public static void main(String args[]) {
        done = false;
        new Thread() {
            public void run() {
            try {
                Thread.sleep(1000); // dummy work load
            } catch (Exception e) {
                done = true;
            }
            done = true;
            }
        }.start();
        while (!done);
        System.out.println("bye");
    }
}

Why it doesn't end

Dog

Posted 2014-03-16T02:59:32.170

Reputation: 241

1nice quirk :P; there are always some of them in each language – masterX244 – 2014-03-19T20:37:16.677

Though depending on your VM this might work just as expected. – Paŭlo Ebermann – 2014-03-24T11:31:35.720

3

JavaScript

while(true)
    if(NaN == NaN)
        break;
    else
        console.log("Batman");

A funny property of the global NaN (Not a Number) object in JavaScript is that it is not equal to itsself. To test if a number is NaN one must use isNaN(). It's also amusing that typeof(NaN) returns "number".

hetzi

Posted 2014-03-16T02:59:32.170

Reputation: 131

The behaviour is actually part of the IEEE754 spec for floating point behaviour, which is used in many languages (C++, Java, .Net, etc) and is the usual way to represent floating point numbers in binary. Javascript uses dynamic typing, so a variable can contain a numeric value, a string value or an object reference (e.g. an array). A NaN is still a numeric type of value, which is why its type is Number - it's not an empty string or a Null object. – Phil H – 2014-12-17T16:26:55.930

It's kind of funny that the type of NaN is actually number. – hetzi – 2014-12-17T16:28:47.857

3

C

This prints numbers from 0 to 9. Or at least it should...

#include <stdio.h>

int main() {
    int i;
    char line[12]; // "Iteration: x"

    for(i = 0; i < 10; i++) {
        sprintf(line, "Iteration: %d", i);
        puts(line);
    }

    return 0;
}

This is a classic off-by-one error triggering a stack overflow. The string is indeed 12 characters long, but the programmer forgot about the NULL terminator inserted by sprintf! On GCC, local variables are pushed to the stack in declaration order. Other compilers may order the variables differently. Since the stack grows backwards, this means i is after line in memory. The null byte overwrites the least significant byte of i. At the end of the block, i is always 0. i is incremented and it loops forever with i = 1.

Andrea Biondo

Posted 2014-03-16T02:59:32.170

Reputation: 1 452

2

C

int main(void)
{
        float count = 0;
        while(count < 33554432L)
        {
                count++;
        }
        return 0;
}

Floating-point numbers have limited precision. Under IEEE 754 floating-point math, a single-precision float only has 24 bits of precision: the largest integer that can be represented exactly is 16,777,216. 16777216 + 1 = 16777216.

Mark

Posted 2014-03-16T02:59:32.170

Reputation: 2 099

6Not, in fact, true in either theory or practice. Clause 5.2.4.2.2 of the C standard says that the accuracy of these floating point operations is implementation-defined, and implementations are furthermore allowed to evaluate float arithmetic using double or even long double precision. Clause 5.1.2.3 allows implementations to omit unneeded side-effects. The clang compiler, with optimization turned on, does exactly this. It optimizes away the entire loop and the loop control variable, yielding a program that terminates with return 0. The emitted (x86) machine code is 2 instructions. – JdeBP – 2014-03-18T14:48:37.247

2Moreover, if the loop doesn't have any side effects (like here where the count variable isn't used), compiler may assume that loop does terminate. – Ruslan – 2014-03-19T09:20:22.483

@JdeBP C requires assignments and casts to drop any excess precision, and no matter what precision float has on a particular implementation, there will be some value for which adding 1 has no effect. 5.2.4.2.2p8: "Except for assignment and cast (which remove all extra range and precision), the values of operations with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type." Ruslan's comment seems like the only reason it can terminate. – hvd – 2014-03-19T23:48:05.223

1Too many float related answers! – Anonymous Pi – 2014-03-21T02:07:52.757

Ruslan's comment is a restatement of what I said, where I explicitly pointed to clause 5.1.2.3. Compilers don't solve the halting problem. They eliminate code with unneeded side effects. Here, they recognize a canonical iteration statement with a non-constant controlling expression and no needed side-effects (nor synchronization operations), and eliminate it. Clause 6.8.5 explains how. – JdeBP – 2014-03-22T08:59:42.700

Also: The wording that you italicized and and the wording in clause 6.8.5 are new for the 2011 standard, the latter introduced by Hans Boehm and Lawrence Crowl in 2009 (N1349). Note that, as explained in the Rationale, prior revisions of the language pretty much required that float expressions be evaluated as double, and had no such narrowing requirement upon assignments. – JdeBP – 2014-03-22T09:03:22.470

2

C#

Perhaps too obvious, but

class Program
{
    static void Main()
    {
        int x = 0;
        while (x * x != 1000)
            x++;
        System.Console.WriteLine("Square root of 1000 is " + x);
    }
}

The square root of 1000 is not an integer, so it will never find it. It's just going to loop forever, assuming overflows aren't checked (the default is unchecked). So like I said, perhaps too obvious. But when I first saw it, I was pretty sure it was going to terminate - 1000 looks as though it should have an integer square root - to me, anyway.

harold

Posted 2014-03-16T02:59:32.170

Reputation: 1 199

2

Postscript

hello.ps:

/hello
{
    (Hello, world\n) print
    quit
}
dup 2 3 index cvx put def

hello

This prints "Hello, world" forever. To try it with ghostscript:

gs -sDEVICE=nullpage hello.ps

dup 2 3 index cvx put replaces the procedure's call to quit with a recursive call to procedure hello. Since postscript does tail call optimization, this runs forever without overflowing the stack.

Wayne Conrad

Posted 2014-03-16T02:59:32.170

Reputation: 163

@luserdroog Thanks for the kind words, and for helping me learn this technique.

– Wayne Conrad – 2014-03-26T13:51:56.017

2

TeX (Plain): Typesetting The Song That Never Ends

Compile with pdftex. It is not obfuscated (besides, well, being written in TeX) and actually does end, as pdftex stops after somewhat about 2.6 million pages...

\font\bigrm=cmr12 at 14pt
\centerline{\bigrm The Song That Never Ends}
\bigskip
\def\songthatneverend{
\noindent This is the song that never ends.\hfil\break
Yes, it goes on and on my friends.\hfil\break
Some people started singing it not knowing what it was,\hfil\break
and they'll continue singing it forever just because\smallskip

\expandafter\songthatneverend}
\songthatneverend
\bye

Daniel

Posted 2014-03-16T02:59:32.170

Reputation: 231

1Hmm, this is not that underhanded, I would say. – Paŭlo Ebermann – 2014-05-31T23:01:05.527

@PaŭloEbermann: No it isn't. It is just TeX :-) – Daniel – 2014-06-03T11:20:41.367

2

Ruby

if p
  //misses
  raise 'Unreachable'
end

while p //nonsense, Kernel#p always returns nil, which is falsey, so this will immediately terminate.
  puts 'Looping'
end

puts 'Done looping'

histocrat

Posted 2014-03-16T02:59:32.170

Reputation: 20 600

1

Batch

This loops forever outputting Hello.

@echo off
for /l %%a in (0,0,1) do echo Hello.

The for loop tries to count from 0 to 0 incrementing by 1 - (0,0,1). So it never reaches zero.

Or if you want to cause the prompt to crash.

@echo off
for /l %%a in (0,1,1) do call %%%%a
:1
echo END

--

h:\uprof>end.bat
******  B A T C H   R E C U R S I O N  exceeds STACK limits ******
Recursion Count=477, Stack Usage=90 percent
******       B A T C H   PROCESSING IS   A B O R T E D      ******

unclemeat

Posted 2014-03-16T02:59:32.170

Reputation: 2 302

1

Javascript

Here's a typical beginner's programming exercise.

Continually repeat a sequence of 1..n1, until you've output a total of n2 numbers. For example, looping through 1..3 where the total quantity is 10 would produce this:

1 2 3 1 2 3 1 2 3 1

Below is a solution that uses a currying function. It's simple, elegant, and will hang your browser :-)

function output(msg) {
    $('<span></span>').text(msg).appendTo($('#output'));
}

function loopThroughSequence(max) {
    i = 0;
    return function() {
        if(i >= max) {
            i = 0;
        }
        return ++i;
    }
}

var getNextInSequence = loopThroughSequence(3);
for(var i = 0; i < 10; ++i) {
    output(' ' + getNextInSequence());
}

Note that loopThroughSequence forgets to declare i in scope. (It needed to preceed 'i' with the 'var' keyword.) Instead, it uses the i value declared below it in the for loop, and continually resets it back to zero.

Andrew Shepherd

Posted 2014-03-16T02:59:32.170

Reputation: 211

A function that returns another function ... it ain't that simple. And the double loop "i" has been posted by @Aleksi Torhamo – rafaelcastrocouto – 2014-03-20T19:11:56.483

1

C++

#include<fstream.h>
int main()
{ 
 char ch[80];
 ifstream fin("evil.txt");
 while(fin)
 {
  fin.get(ch,50); //read by lines
  cout<<ch;
 } //nothing wrong, right? wrong.
 return 0;
}

evil.txt contains following data :

hello.
I am awesome.

fin.get() leaves a '\n' in input stream. The rest is Elementary, my dear.

evil999man

Posted 2014-03-16T02:59:32.170

Reputation: 111

1

How about this...

#include<stdio.h>

void main(){
while((10*5/3)!=(10/3*5))
printf("In a loop\n");
}

Mathematically (10/3)*5==(10*5)/3;

Vishwanath gowda k

Posted 2014-03-16T02:59:32.170

Reputation: 119

You can omit the parentheses, and even use the same type for both a and b. But it is still quite obvious where the problem is, you should hide it in some piece of program which seems to be useful. – Paŭlo Ebermann – 2014-03-24T11:09:54.173

1

Whitespace

(actual working code follows)

Readable version:

FSSSSSTTFFSFSSSSSTTFF
Where F is linefeed, S is space and T is tab

Darrell Teague

Posted 2014-03-16T02:59:32.170

Reputation: 111

1The Stack Exchange platform doesn't support Whitespace. You may want to use normalized Whitespace, or paste the script on the platform that does support it. – Konrad Borowski – 2014-03-23T13:38:08.513

1The code is there when I try to edit but apparently does not render properly. In any case, it is more a positional answer that the OP's question can be (maybe best) answered using Whitespace. – Darrell Teague – 2014-03-23T14:19:12.033

1

Haskell

This is just a simple program to illustrate return statements. Since the return statement ends the function, it doesn't run anything after it.

sayHello :: IO String
sayHello = do
    return "Hello!"
    sayHello

main = do
    hello <- sayHello
    putStrLn hello

Return statements don't end functions, unlike in other languages.

Aearnus

Posted 2014-03-16T02:59:32.170

Reputation: 251

1

c#

    public void MemoryEfficientCountTo256()
    {
        for (byte i = 0; i <= 255; i++)
        {
            Console.WriteLine(i);
        }
    }

This is from a stackoverflow question. A byte can never be 256, so adding one takes it back to 0

Ewan

Posted 2014-03-16T02:59:32.170

Reputation: 151

0

C

int main(void) {
  int x;
  while(x<=10) x+=1;
}

from my experience this thing loops indefinitely only after 4 years of stable production at 3AM on a Saturday and once it loops for first time no system reboot can make it go away and within 15 minutes it happens to all high availability servers, dumping the entire production stack offline for a day.

bbozo

Posted 2014-03-16T02:59:32.170

Reputation: 167

Why the downvote? This is a variation of a real deal, the int usually gets randomly allocated on a zero-padded memory segment, but just sometimes gets allocated where there's garbage already so incrementing never reaches 10 – bbozo – 2014-03-17T10:37:43.820

2Compilation fails due to missing (). – orion – 2014-03-17T10:45:30.227

@bbozo it ought to reach 10 anyway, even if it starts with garbage, due to wraparound. – imallett – 2014-03-17T23:21:04.407

@IanMallett: Not necessarily. Accessing an uninitialized non-static variable is undefined behavior. So is signed integer overflow. – Dennis – 2014-03-18T02:11:36.690

@Dennis technically true, but practically not. Every low-level C compiler is going to implement int as a 16- or 32-bit signed data type (and probably the latter) with either ones-complement or twos-complement overflow behavior (and probably the latter). The OP mentioned nothing about needing a special platform/compiler, so I'm assuming it's a canonical one. – imallett – 2014-03-18T02:16:31.627

2

@IanMallett: Why does integer overflow on x86 with GCC cause an infinite loop?

– Dennis – 2014-03-18T02:20:19.690

@Dennis: So the compiler can make use of the fact that's it's undefined behavior to optimize. Thanks! – imallett – 2014-03-18T02:32:21.777

0

Java

public class Main {
    public static void main(String[] args) {
        try{
        double i=1.0/0.0;
            while(i==i+1){  //weired condition should never be true
                System.out.println("This should never be printed");
            }
        }catch (ArithmeticException e){
            System.out.println("Caught divide by 0 exception");

        }
    }
}

Manu Viswam

Posted 2014-03-16T02:59:32.170

Reputation: 111

The classic NaN :D – Silviu Burcea – 2014-03-17T12:51:49.497

@SilviuBurcea Not a NaN (NaN != NaN), but an infinity. – Paŭlo Ebermann – 2014-03-24T12:03:12.830

This should be hidden better. – Paŭlo Ebermann – 2014-03-24T12:03:35.437

0

Ruby

This is a super efficient piece of code that simulates a dice.

def almost_dice
  rand(7) # will output a number between 0 and 6. 
end

#I want a dice that outputs a number between 1 and 6, so I have no other choice, right?
def proper_dice
  d = almost_dice
  while d = 0
    d = almost_dice #Eventually, I'll get d != 0
  end
  return d
end

puts proper_dice

In ruby what could look like a test : d = 0 is actually an assignment. Since the assignement always succeed, then the test always returns true, hence the infinite loop

aherve

Posted 2014-03-16T02:59:32.170

Reputation: 181

Answer: http://i.stack.imgur.com/DDifD.png

– Riking – 2014-03-17T17:54:19.503

Same trick works the same way in C – Glenn Randers-Pehrson – 2014-03-18T03:23:59.060

@GlennRanders-Pehrson no, in C the assignment would have the value 0 (which is falsy), so it wouldn't loop at all. – Paŭlo Ebermann – 2014-03-24T11:52:29.790

@PaŭloEbermann Right, it's the same trick (mistaking "=" for "=="), but not exactly the same, as you said. – Glenn Randers-Pehrson – 2014-03-24T14:04:41.570

0

C#

Let's take a page from this answer: https://codegolf.stackexchange.com/a/24376/16729 but do the computation on a background thread in the class constructor!

class BackgroundSummer
{
  static int sum;
  static BackgroundSummer() 
  {
    // Let's compute the sum on another thread!
    var thread = new System.Threading.Thread(ComputeSum);
    thread.Start();
    thread.Join();
  }

  static void ComputeSum() 
  { /* omitted: compute the sum here */ }

  static void Main() 
  { }
}

An explanation of why this runs forever is here: http://ericlippert.com/2013/01/31/the-no-lock-deadlock/

Eric Lippert

Posted 2014-03-16T02:59:32.170

Reputation: 2 805

0

Scala

var break = false
for(i <- Stream.from(0) if !break) {
  break = i >= 10
}
println("Well done!")

Infinite streams will continue to be evaluated even if break is true.

Or the second one.

var g = 6
def counter: Int = {
  g -= 2
  g
}
def test() = {
  val t = ListBuffer('s','t','a','r','t',' ','e','m','p','t','y')
  var i = t mkString // returns "start empty"
  var l = ListBuffer[Int]()
  while(i != "42") i = (l += counter) mkString // returns "42 after two iterations"
  s"$i should equal 42"
}
println(test())

mkString captures the second argument as a separator, here s"$i should equal 42". So the value of $i is never "42" but goes indefinitely.

Mikaël Mayer

Posted 2014-03-16T02:59:32.170

Reputation: 1 765

0

wxpython

"Hello World" example that fails to exit.

import sys
import time
import wx
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub

class LoggerWindow(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Logger")
        self._log = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        pub.subscribe(self.OnLogMessage, "LOG_MESSAGE")

    def OnLogMessage(self, msg):
        self._log.AppendText(msg)


class GUI(wx.Frame):
    def __init__(self):         
        wx.Frame.__init__(self, None, title="Demo GUI - Hello World")  
        self._logger = LoggerWindow()
        pub.sendMessage("LOG_MESSAGE", msg="GUI Starting")

        # Set up the Hello World message
        self._display = wx.TextCtrl(self, -1, size=(400,20), style=wx.TE_MULTILINE)
        self._display.AppendText("Hello World!")

        # Show it for a while
        self.Show()
        time.sleep(10)

        # Done
        self.Destroy()


App = wx.App()
Gui = GUI()
App.MainLoop()

The log window, while not showing, keeps existing, so the "GUI" window disappears but the app keeps running. I had intended for this to be another example of "not using a loop", but obviously I am using a loop!

GreenAsJade

Posted 2014-03-16T02:59:32.170

Reputation: 333

0

Python

def sum(first, add=[]):
    add.append(first)
    sum = 0
    for el in add:
        sum+= el
    print sum
    return add

if __name__ == '__main__':
    #init
    add = sum(1)
    for el in add:
        sum(el)

this will loop forever due to the fact that expressions in default arguments are calculated when the function is defined, not when it’s called. So the list will grow until the user terminate the script.

le_vine

Posted 2014-03-16T02:59:32.170

Reputation: 701

0

Java

public class Looper {
    public static final int END = Integer.MAX_VALUE;
    public static final int START = END - 100;

    public static void main(String[] args) {
        int count = 0;
        for (int i = START; i <= END; i++)
            count++;
        System.out.println(count);
    }
}

This program was blatantly copied from Bloch and Gafter's Java Puzzlers.

The expression i <= Integer.MAX_VALUE is a tautology, at least if i is an int. By definition, no integer can be greater than Integer.MAX_VALUE.

tbodt

Posted 2014-03-16T02:59:32.170

Reputation: 2 176

0

Tcl

set i 1
while $i<=10 {
    puts $i
    incr i
}

I forgot to brace my expression, so $i will only be substituted once, when while is called

Johannes Kuhn

Posted 2014-03-16T02:59:32.170

Reputation: 7 122

Also, no increment? – Paŭlo Ebermann – 2014-03-24T11:27:38.667

Ohh, forgot the increment. Added. – Johannes Kuhn – 2014-03-24T12:16:50.350

0

JAVASCRIPT

found this while doing my project

function weirdCode(){
  var myarray= ["test",123,false];
  var myarray2 = myarray;
  myarray2[2] = !myarray2[2];
  while(myarray.toString() == myarray2.toString()){
    console.log("shouldn't myarray[2] == false? but it is "+myarray[2]+". but i only edit myarray2, which is "+myarray2[2]);
  }
  console.log("this will never called");
}
weirdCode();

at line "var myarray2 = myarray;" it should be "var myarray2 = myarray.slice()", cause it will be referring the var to myarray, like sharing a var

wuiyang

Posted 2014-03-16T02:59:32.170

Reputation: 371

Another obvious one ... myarray2 = myarray makes it ease to see. – rafaelcastrocouto – 2014-03-20T19:01:39.020

on some coding language, copying an array are 'var CopyOfAnArray = OriginalArray;' – wuiyang – 2014-03-21T16:36:41.150

well .. not in js! – rafaelcastrocouto – 2014-03-21T16:51:39.070

0

JAVASCRIPT

 var x = 1; while(x != 0) x -= 0.1;

x = 1;
x - 0.1 = 0.9;
x - 0.1 = 0.8;
x - 0.1 = 0.7000000000000001
WHAT!!!!!

Now more about it

rafaelcastrocouto

Posted 2014-03-16T02:59:32.170

Reputation: 315

Almost literally this answer http://codegolf.stackexchange.com/a/24386/16874

– Milo – 2014-03-23T06:46:56.780

I usually only read JS answers ... you are 100% right, it's the same ... just different languages. – rafaelcastrocouto – 2014-03-23T10:48:14.963

0

Java, equal but not?

import java.util.HashMap;
import java.util.Map;

public class Endless {
    static class A {
        public A(int a) {
            b = a;
        }

        int b;
        @Override
        public boolean equals(Object obj) {
            return obj != null && (obj instanceof A) && ((A)obj).b == b;
        }
    }

    public static void main(String args[]) {
        Map<A,String> map = new HashMap<A, String>();
        A a = new A(1);
        A sameA = new A(1);

        System.out.println("a is sameA?" + a.equals( sameA ));

        map.put(a, "look ma, no hands!");

        while (!map.containsKey(sameA)){
            //we never get here, do we?
        }
        System.out.println("Done!");
    }
}

RobAu

Posted 2014-03-16T02:59:32.170

Reputation: 641

While it is not obvious why the loop condition is true, it is quite clear that the problem must be there. I recommend hiding it better in a program piece which seems to do something useful. – Paŭlo Ebermann – 2014-03-24T11:12:47.073

0

How about a fork bomb?

:(){ :|: &};:

Wordzilla

Posted 2014-03-16T02:59:32.170

Reputation: 253

2The ubiquitousness of the fork bomb makes this rather obviously non-terminating. – Fraxtil – 2014-03-23T03:07:18.870

0

C

This one works..

#include<stdio.h>

void main(){
double a=10;
float b=10;
while(a/3!=b/3)
printf("Infinite loop");
}

Vishwanath gowda k

Posted 2014-03-16T02:59:32.170

Reputation: 119

Can you add the language? – Milo – 2014-03-25T05:05:59.857

1And similar things have been done already pertaining to floating point precision. – Milo – 2014-03-25T05:06:42.950

0

In Ruby:

x = "a"

while ! x.equal?("aaaaaaaa")
   x += "a"
end

In Ruby, the .equal? method checks for object equality, not value equlity. "aaaaaaaa" is a unique object, and thus has a different object ID than x. Because of this the statement will never be true.

Another one:

a = b = "a"

while a == b
    b << "a"
end

Here a and b gets the reference to the same object. The << method actually changes the value at the location where the object is referencing, and does not create a new object as most other methods does. Since both a and b references the same location, the values will always be the same.

Automatico

Posted 2014-03-16T02:59:32.170

Reputation: 171

0

Powershell

I feel like counting from one to a hundred. Don't you?

$i = 1;
for($i -lt 100;$i++){$i}

...Wait a minute, that's way more than a hundred printing out...

...

...

This should be fairly simple to figure out, and I found it amusing, at least.

fuandon

Posted 2014-03-16T02:59:32.170

Reputation: 309

0

C

#include <stdio.h>

int count_bits(unsigned int field)
    {
    unsigned int a = 1;
    int count = 0;

    while (1)
        {
        switch (a)
            {
            case 1 << 31: /* MAX_UINT32 */
                {
                break;
                }
            default:
                {
                if (field & a) count++;
                a <<= 1;
                }
            }
        };
    return count;
    }

int main(int argc, char *argv[])
    {
    printf("%d\n", count_bits(0xdeadbeef));
    return 0;
    }

In C and C++ case is a jump target. The break breaks the switch, but not the while. Substituting break; with return count; will work.

urzeit

Posted 2014-03-16T02:59:32.170

Reputation: 1 297

0

Java, with OpenCV

(just a snippet)

VideoCapture camera = new VideoCapture(0);
Mat frame = new Mat();
while(frame.get(1, 1)[0]<200)camera.read(frame);

Java OpenCV stores pixel values from 0 to 1, not 0 to 255.

Lucas

Posted 2014-03-16T02:59:32.170

Reputation: 665

0

Lua

Totaly boring, but I thought it was still interesting:

-- Example of stack overflow using recursion
-- Function foo: this function will call itself forever: foo(foo(foo(foo(foo...
function foo() -- Our recursive function
    return foo() -- Our recursive call, this will cause the stack to overflow
end
pcall(foo) -- pcall will call foo in protected mode, catching stack overflows.
print("Stackoverflow! Avoid infinite recursion!") -- Use infinite recursion wisely

How does it work?

I dont have a clue. I think its optimized to something like:

call main
exit
label foo:
jmp foo
label main:
push foo
call pcall
push "Stackoverflow! Avoid infinite recursion!"
call print

Notes:

  • This is not assembly or lua bytecode or anthing
  • Exponential recursion will result in a stack overflow: foo(foo()). I think this is because this will call foo before it will jmp foo?
  • Can someone please make a C function and try it out with that? I would love to know if it will result in a overflow or not. (I am guessing it will, but you never know...)

YoYoYonnY

Posted 2014-03-16T02:59:32.170

Reputation: 1 173

0

C++'s rules can be pesky some times

a.cpp:
#include "Shape.h" // includes class Shape, with virtual functions on it

int callback(int value, Shape* s)
{
    // aggregates areas
    return value + s->getArea();
}

// Some boring work... we don't even call this function
int aggrigateAreas(Shape* begin, Shape* end)
{
    int rval = 0;
    for (Shape* iter = begin; iter != end; iter++)
        rval = callback(rval, iter);
    return rval;
}


b.cpp:
#include "Shape.h"

int callback(Shape* s)
{
    // aggrigate perimieters
    return s->getPerimiter();
}

// doSomethingImportant will actually do something for us
int doSomethingImportant(Shape* s)
{
    return callback(s); // this was more complicated in real life
}

main.cpp
#include "Shape.h"
#include <iostream>
int doSomethingImportant(Shape* s);

int main() {
    Square s(1); // square with side length 1
    std::cout << doSomethingImportant(&s); // should print 4, right?
    return 0;
}

Sadly, C/C++ is rather unfriendly if you have two functions in different translation units with different names. They call it a ODR violation (One Definition Rule) and it's Undefined Behavior. As it so happens, if the linker is not being kind to you today, your call to callback in doSomethingImportant can end up calling the callback in a.cpp. This is bad enough, but they also don't have the same signatures. s may get some garbage value, such as something which causes the virtual function lookup of getArea() to return the address just before main, creating an infinite loop when called. It even gets a few broken opcodes just right to maladjust the stack back to its initials stack height, so you don't even get a sane stack overflow.

Is this against the rules of code golf? Maybe. I am trying to claim a win by getting very unlucky with a compiler's handling of undefined behavior. Technically that's outside of the spec of the language.

However, the scars I put into my cubicle walls that day, dug deep with my fingers as I screamed in agony remain. Dug over the course of that whole 12 hour work day, with the debugger taunting me as I went (You're {bleep}ing kidding me! Why did the debugger put me back in a.cpp again! I commented out all calls to that file wholesale! Maybe I should recompile the world again)... that has to qualify as "underhanded" somehow, right? Please?

I will not forget to open the anonymous namespace to store my callbacks

I will not forget to open the anonymous namespace to store my callbacks

I will not forget to open the anonymous namespace to store my callbacks

Cort Ammon

Posted 2014-03-16T02:59:32.170

Reputation: 508

0

c++

A simple program, to show how operator overloading works:

EDIT: this is inspired by BF

#include <iostream>
class ops
{
public:
    int val=1;
    ops operator * (ops rhs){val++; return *this;}
    ops operator & (ops rhs){val-=3; return *this;}
};
int main() {
    ops a;
    while (a.val>0) 
    {
        a=a**&a; //call operator* twice and operator& once, net effect of subtracting 1
        std::cout<<a.val;
    }
    return 0;
}

This calls operator* once and operator& zero times. *&a is the same as a, because of pointers.

Lucas

Posted 2014-03-16T02:59:32.170

Reputation: 665

-2

C#

   for (; ; )
    {
        try
        {
            string text = "SomeText";
            System.IO.File.WriteAllText(@"c:\Pathwith?.txt", text);

            break;
        }
        catch { }
    }

Menelaos Vergis

Posted 2014-03-16T02:59:32.170

Reputation: 105

1Well of course it doesn't terminate... why would it? – orion – 2014-03-17T11:01:34.553

Isn't this the purpose of the assignment? It should have ended if the file existed but it will throw exception and will never end – Menelaos Vergis – 2014-03-17T11:03:56.320

It is, it's just not very surprising because it very obviously references a very particular file that most likely doesn't exist. – orion – 2014-03-17T11:17:15.630

Now is it better? – Menelaos Vergis – 2014-03-17T12:20:45.177

Please be sure to include a language header with your answers, e.g. ## Java or ## C. Welcome to the site! – Jonathan Van Matre – 2014-03-17T12:26:43.230

-2

C++ - Lame

Yay I is pro C++ I learnt for loop real quik now lets make cool program that print 1 to 10 cuz I am awesome and totaly did not chose C++ just cuz C doesnt allow for loop.

#include <stdio.h> // 2 lazy 4 std::cout

int main()
{
    int i = 1;
    for (i < 10; i++;)
    {
        printf("%d\n", i);
    }
}

No why I is pro C++ why U dont work I learn for syntax well :(

upvote @fuandon instead, he gave me the idea. This is my second one anyway...

YoYoYonnY

Posted 2014-03-16T02:59:32.170

Reputation: 1 173

2Clever trick. You might want to explain how it works in a spoiler. – isaacg – 2015-05-07T06:11:14.780