93
votes
\$\begingroup\$

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!

\$\endgroup\$
11
  • 6
    \$\begingroup\$ Could someone please explain what I can do to make the question less broad? I am new here. Thank you! \$\endgroup\$
    – Number9
    Commented Mar 16, 2014 at 13:58
  • 6
    \$\begingroup\$ This is just going to be a big list of typos and beginner's mistakes which cause loops. \$\endgroup\$ Commented Mar 17, 2014 at 0:51
  • \$\begingroup\$ 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! \$\endgroup\$ Commented Mar 17, 2014 at 5:35
  • 14
    \$\begingroup\$ I don't know if this counts, but my Microsoft Office is behaving exactly like this at the moment. \$\endgroup\$ Commented Mar 22, 2014 at 11:40
  • 1
    \$\begingroup\$ I'm voting to close this question as off-topic because underhanded challenges are no-longer on-topic here. meta.codegolf.stackexchange.com/a/8326/20469 \$\endgroup\$
    – cat
    Commented Apr 15, 2016 at 14:20

73 Answers 73

182
votes
\$\begingroup\$

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.

\$\endgroup\$
14
  • 13
    \$\begingroup\$ You got me with that one… the (actually) higher-voted examples are all just abusing syntax… but that one is nice! \$\endgroup\$
    – bwoebi
    Commented Mar 17, 2014 at 17:37
  • 4
    \$\begingroup\$ Chrome on Kubuntu became unresponsive, hang everything and I had to hard reset :) \$\endgroup\$ Commented Mar 19, 2014 at 10:08
  • 4
    \$\begingroup\$ @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. \$\endgroup\$ Commented Mar 20, 2014 at 4:52
  • 2
    \$\begingroup\$ There is not check on the fact that value is actually under 100 so it stops normally when you enter "100" :'-( \$\endgroup\$ Commented Mar 21, 2014 at 17:18
  • 1
    \$\begingroup\$ @Sankalp, the + operator here is the string concatenation, not the addition. \$\endgroup\$
    – Michael M.
    Commented Feb 7, 2015 at 9:48
87
votes
\$\begingroup\$

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

\$\endgroup\$
8
  • 8
    \$\begingroup\$ Haha, I figured this one out before looking at the solution spoiler. :P \$\endgroup\$
    – Joe Z.
    Commented Mar 17, 2014 at 14:29
  • 54
    \$\begingroup\$ Why did you pass up such an excellent opportunity to use the "goes to" operator? (x --> 0) \$\endgroup\$
    – corsiKa
    Commented Mar 17, 2014 at 16:57
  • 2
    \$\begingroup\$ Oh wow. This is wonderfully evil. Took me four reads through to find it. \$\endgroup\$
    – Patrick M
    Commented Mar 19, 2014 at 8:55
  • 1
    \$\begingroup\$ @JoeZ. Way too easy. The most upvoted solution was better. That one I didn't find. \$\endgroup\$ Commented Mar 21, 2014 at 1:59
  • 3
    \$\begingroup\$ @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. tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html \$\endgroup\$
    – nemec
    Commented Mar 22, 2014 at 2:28
84
votes
\$\begingroup\$

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.

\$\endgroup\$
7
  • 3
    \$\begingroup\$ Could you add a better explanation of why this never terminates? Please go into depth about "variable hoisting" :) \$\endgroup\$
    – Number9
    Commented Mar 16, 2014 at 22:32
  • 1
    \$\begingroup\$ @Number9 I hope that helps, google has much better examples than this ;) \$\endgroup\$
    – Newbrict
    Commented Mar 16, 2014 at 22:39
  • 25
    \$\begingroup\$ Holy shit this is even worse than semicolon insertion. +1! \$\endgroup\$
    – tomsmeding
    Commented Mar 17, 2014 at 12:03
  • 2
    \$\begingroup\$ Only 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. \$\endgroup\$
    – PeterT
    Commented Mar 17, 2014 at 16:19
  • 2
    \$\begingroup\$ You 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. \$\endgroup\$ Commented Mar 22, 2014 at 21:53
49
votes
\$\begingroup\$

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

\$\endgroup\$
10
  • 12
    \$\begingroup\$ Oh, the l is supposed to look like a 1! I'm stupid. :\ \$\endgroup\$
    – Joe Z.
    Commented Mar 17, 2014 at 14:27
  • 6
    \$\begingroup\$ Suggestion 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) \$\endgroup\$ Commented Mar 17, 2014 at 16:09
  • 3
    \$\begingroup\$ Yeah, it does seem to be quite environment-specific. @Michael's font looks very different to the font on my home computer (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. \$\endgroup\$
    – BenM
    Commented Mar 17, 2014 at 18:41
  • 1
    \$\begingroup\$ FTR, here's what it looks like on my work computer (imgur.com/Opfs3BH - Firefox, Windows 7). I reckon that one could even fool quite astute people. \$\endgroup\$
    – BenM
    Commented Mar 17, 2014 at 20:21
  • 15
    \$\begingroup\$ WHY DO PEOPLE KEEP ABUSING OF CHARACTERS THAT LOOK THE SAME? \$\endgroup\$ Commented Mar 21, 2014 at 2:01
39
votes
\$\begingroup\$

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.

\$\endgroup\$
8
  • 1
    \$\begingroup\$ How does this work? \$\endgroup\$
    – Mohammad
    Commented Mar 17, 2014 at 17:46
  • 5
    \$\begingroup\$ Rounding 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. \$\endgroup\$
    – orion
    Commented Mar 17, 2014 at 18:32
  • 3
    \$\begingroup\$ Not really a rounding error. Floating point values are approximate representations of a number. Performing exact comparisons between approximate values isn't going to work. \$\endgroup\$
    – AKHolland
    Commented Mar 18, 2014 at 19:36
  • 4
    \$\begingroup\$ This is why you (almost) never should compare float/doubles for equality. \$\endgroup\$ Commented Mar 19, 2014 at 5:41
  • 1
    \$\begingroup\$ I was waiting to see this one. Nice. \$\endgroup\$ Commented Mar 19, 2014 at 17:40
33
votes
\$\begingroup\$

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.

\$\endgroup\$
13
  • 5
    \$\begingroup\$ in 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 \$\endgroup\$
    – Einacio
    Commented Mar 17, 2014 at 16:20
  • 6
    \$\begingroup\$ Nice one. +1 for no loops or recursion. \$\endgroup\$ Commented Mar 17, 2014 at 17:11
  • 5
    \$\begingroup\$ No 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. \$\endgroup\$
    – RomanSt
    Commented Mar 18, 2014 at 13:03
  • 6
    \$\begingroup\$ IE11 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! \$\endgroup\$
    – RomanSt
    Commented Mar 18, 2014 at 13:18
  • 1
    \$\begingroup\$ Works normally (no loops) on MSIE11 \$\endgroup\$
    – kinokijuf
    Commented Mar 22, 2014 at 10:10
32
votes
\$\begingroup\$

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.

\$\endgroup\$
9
  • 2
    \$\begingroup\$ Nice one, but compilers normally output a warning for this ;) \$\endgroup\$
    – Synxis
    Commented Mar 17, 2014 at 13:43
  • 2
    \$\begingroup\$ @Synxis Yes compilers do. But only if you turn on compiler warnings. g++ won't warn you about this without them. \$\endgroup\$
    – FDinoff
    Commented Mar 17, 2014 at 13:47
  • 5
    \$\begingroup\$ You should always use -Wall --pedantic anyway. \$\endgroup\$ Commented Mar 17, 2014 at 14:54
  • 3
    \$\begingroup\$ @queueoverflow The warning doesn't show with only those flags. You need -Wsign-compare which can be turned on with -Wextra. \$\endgroup\$
    – FDinoff
    Commented Mar 17, 2014 at 15:04
  • 7
    \$\begingroup\$ One dash on -pedantic. #pedantic \$\endgroup\$ Commented Mar 19, 2014 at 17:39
29
votes
\$\begingroup\$

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

\$\endgroup\$
8
  • \$\begingroup\$ Eventually runs bash out of memory and crashes it \$\endgroup\$ Commented Mar 17, 2014 at 18:14
  • 4
    \$\begingroup\$ Yes, indeed it does. But a crash was kind of allowed by the question :) \$\endgroup\$ Commented Mar 17, 2014 at 21:55
  • \$\begingroup\$ Yes, just an observation :). Upvoted. \$\endgroup\$ Commented Mar 17, 2014 at 22:00
  • \$\begingroup\$ 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 ) \$\endgroup\$ Commented Mar 21, 2014 at 1:16
  • \$\begingroup\$ Correction: yes is just a coreutils program. Not a syscall. \$\endgroup\$
    – mniip
    Commented Mar 22, 2014 at 22:14
28
votes
\$\begingroup\$

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

\$\endgroup\$
4
  • 7
    \$\begingroup\$ I love that there's a story with the solution. \$\endgroup\$
    – jpmc26
    Commented Mar 22, 2014 at 1:55
  • \$\begingroup\$ Haha! I guess it's the only one. Thanks for reading through! \$\endgroup\$
    – Legat
    Commented Mar 22, 2014 at 10:26
  • 1
    \$\begingroup\$ I love you. Feed me with your stories pls :( \$\endgroup\$
    – yyny
    Commented May 1, 2015 at 20:50
  • \$\begingroup\$ This is absolutely brilliant! \$\endgroup\$ Commented May 1, 2015 at 22:26
21
votes
\$\begingroup\$

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

\$\endgroup\$
4
  • 3
    \$\begingroup\$ I hate backtracking regex engines. \$\endgroup\$ Commented Mar 19, 2014 at 17:43
  • 2
    \$\begingroup\$ I 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. \$\endgroup\$
    – null
    Commented Mar 22, 2014 at 12:19
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Commented Mar 22, 2014 at 13:30
  • 1
    \$\begingroup\$ This is so SLICK. \$\endgroup\$
    – alvonellos
    Commented Mar 23, 2014 at 3:53
20
votes
\$\begingroup\$

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.

\$\endgroup\$
4
  • 73
    \$\begingroup\$ I find this obvious. :-) \$\endgroup\$
    – Justin
    Commented Mar 17, 2014 at 1:41
  • 6
    \$\begingroup\$ I 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" \$\endgroup\$
    – Cruncher
    Commented Mar 19, 2014 at 18:24
  • \$\begingroup\$ This needs to be hidden better. \$\endgroup\$ Commented Mar 24, 2014 at 11:48
  • \$\begingroup\$ It is obvious.. \$\endgroup\$
    – Oliver Ni
    Commented Jan 1, 2015 at 22:47
18
votes
\$\begingroup\$

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.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ Too bad this doesn't actually work :-/ \$\endgroup\$ Commented Mar 17, 2014 at 6:38
  • 1
    \$\begingroup\$ How doesn't it work? \$\endgroup\$
    – danmcardle
    Commented Mar 18, 2014 at 1:47
  • \$\begingroup\$ @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. \$\endgroup\$
    – FDinoff
    Commented Mar 18, 2014 at 14:00
  • \$\begingroup\$ Interesting! I didn't realize that this happened. I don't venture into gobbling-all-memory territory all that often. \$\endgroup\$
    – danmcardle
    Commented Mar 18, 2014 at 16:07
  • 4
    \$\begingroup\$ That's still a valid solution: it doesn't exit, it runs as long as it can till the system can't support it anymore... \$\endgroup\$ Commented Mar 19, 2014 at 1:18
16
votes
\$\begingroup\$

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Maybe 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". \$\endgroup\$
    – asteri
    Commented Mar 17, 2014 at 17:15
  • 4
    \$\begingroup\$ if 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 \$\endgroup\$
    – masterX244
    Commented Mar 17, 2014 at 17:21
  • \$\begingroup\$ Ah, gotcha. Nice! +1 \$\endgroup\$
    – asteri
    Commented Mar 17, 2014 at 17:57
15
votes
\$\begingroup\$

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

\$\endgroup\$
8
  • 9
    \$\begingroup\$ You sneaky bastard, goto is innocent in this :) \$\endgroup\$
    – orion
    Commented Mar 17, 2014 at 10:36
  • \$\begingroup\$ is the random() the vodoo used? \$\endgroup\$
    – masterX244
    Commented Mar 17, 2014 at 15:47
  • 1
    \$\begingroup\$ ahh, "2" !=2 ; got it \$\endgroup\$
    – masterX244
    Commented Mar 17, 2014 at 15:55
  • 2
    \$\begingroup\$ Well "2" probably can't ever be 2, but if you used a bigger number (and a multiple of at least 4), it could happen ;) \$\endgroup\$
    – orion
    Commented Mar 17, 2014 at 18:34
  • 1
    \$\begingroup\$ @orion: Yes you are right, it could be. And goto is still evil, but bad type castings are even more evil! \$\endgroup\$ Commented Mar 17, 2014 at 21:49
12
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Perhaps use int32_t; a 64 bit int would take really, really, really long (585 years if each iteration takes a nanosecond). \$\endgroup\$ Commented Mar 25, 2014 at 2:55
11
votes
\$\begingroup\$

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.

\$\endgroup\$
12
  • \$\begingroup\$ This is a too basic example of an infinite loop. \$\endgroup\$ Commented Mar 16, 2014 at 6:24
  • 64
    \$\begingroup\$ Those Trigraphs are sooo overused here :( \$\endgroup\$
    – TimWolla
    Commented Mar 16, 2014 at 20:29
  • 75
    \$\begingroup\$ I almost feel like trigraphs should be put in Standard Loopholes Which Are No Longer Funny. \$\endgroup\$ Commented Mar 16, 2014 at 21:41
  • 6
    \$\begingroup\$ @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. \$\endgroup\$ Commented Mar 16, 2014 at 22:43
  • 4
    \$\begingroup\$ @undergroundmonorail Posted \$\endgroup\$
    – Justin
    Commented Mar 17, 2014 at 2:45
11
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • 5
    \$\begingroup\$ Given that some Java guys still consider C++ operator-overloading as evil ... \$\endgroup\$
    – Daniel
    Commented Mar 23, 2014 at 9:01
  • \$\begingroup\$ You don't need the initialization = new Integer(0), as you are initializing the values afterwards anyways. (This might make the reason less obvious.) \$\endgroup\$ Commented Mar 24, 2014 at 10:19
  • \$\begingroup\$ @PaŭloEbermann: Good point, I have edited the code. \$\endgroup\$
    – Daniel
    Commented Mar 24, 2014 at 10:26
8
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Do languages at once...impressive. \$\endgroup\$ Commented Mar 25, 2014 at 2:57
7
votes
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ What language is this? \$\endgroup\$
    – RononDex
    Commented Mar 17, 2014 at 10:11
  • \$\begingroup\$ @ronondex Javascript \$\endgroup\$
    – tomsmeding
    Commented Mar 17, 2014 at 12:04
  • 1
    \$\begingroup\$ Ah, yes, it's Javascript. I remembered to enable the syntax hilighting but had to forget to put it in the title too :) \$\endgroup\$ Commented Mar 17, 2014 at 16:37
  • 1
    \$\begingroup\$ I find this obvious. :-) \$\endgroup\$
    – user15260
    Commented Mar 20, 2014 at 12:43
  • \$\begingroup\$ @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. :) \$\endgroup\$ Commented Mar 20, 2014 at 17:57
7
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 24, 2014 at 11:19
  • \$\begingroup\$ @PaŭloEbermann: Great idea. \$\endgroup\$ Commented Mar 24, 2014 at 18:27
  • \$\begingroup\$ I use this trick in my classroom, with printable unsigned characters between 32 and 128. :) \$\endgroup\$
    – cpri
    Commented Jun 4, 2014 at 13:42
6
votes
\$\begingroup\$

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;
}
\$\endgroup\$
6
  • \$\begingroup\$ I don't get this? Is it about using. =instead of == ? \$\endgroup\$
    – Mohammad
    Commented Mar 17, 2014 at 17:53
  • \$\begingroup\$ @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. \$\endgroup\$
    – CompuChip
    Commented Mar 17, 2014 at 18:43
  • 3
    \$\begingroup\$ This is ever more reason to use yoda conditions. \$\endgroup\$ Commented Mar 20, 2014 at 3:51
  • \$\begingroup\$ @RyanEdwardDougherty Haha like that I never heard them being called. For the morning laugh thanks. \$\endgroup\$
    – CompuChip
    Commented Mar 20, 2014 at 7:53
  • \$\begingroup\$ @RyanEdwardDougherty: Of course == true (or Yoda-style true ==) is redundant anyway, and the condition should simply read while (keepGoing). \$\endgroup\$
    – celtschk
    Commented Mar 23, 2014 at 19:03
6
votes
\$\begingroup\$

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

\$\endgroup\$
6
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 17, 2014 at 17:54
  • 1
    \$\begingroup\$ Those kinds of things... Like when my elseif didn't work because it was elif. \$\endgroup\$ Commented Mar 17, 2014 at 18:04
  • \$\begingroup\$ Thanks @moose updated print statement and the spoiler message \$\endgroup\$
    – Willem
    Commented Mar 17, 2014 at 19:10
5
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • 5
    \$\begingroup\$ Extra parentheses in return statement, yuck. \$\endgroup\$ Commented Mar 19, 2014 at 17:48
  • 1
    \$\begingroup\$ This will eventually segfault, though. \$\endgroup\$ Commented May 1, 2015 at 22:31
5
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ marking it as lang-hs instead of lang-haskell seems to work better (it's one of the extensions in the google prettifier) \$\endgroup\$
    – Einacio
    Commented Mar 17, 2014 at 16:31
5
votes
\$\begingroup\$

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.

\$\endgroup\$
5
votes
\$\begingroup\$

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.

\$\endgroup\$
5
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ This usually takes me at least 5 minutes to debug. I hate it when I did this. \$\endgroup\$
    – user12205
    Commented Mar 22, 2014 at 6:50
4
votes
\$\begingroup\$

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

\$\endgroup\$
4
votes
\$\begingroup\$

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)

\$\endgroup\$
3
  • \$\begingroup\$ I don't see a problem here. I ran it and it worked fine. What am I missing? \$\endgroup\$ Commented Mar 19, 2014 at 0:19
  • \$\begingroup\$ 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! \$\endgroup\$
    – user15260
    Commented Mar 20, 2014 at 19:10
  • \$\begingroup\$ 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 \$\endgroup\$
    – yyny
    Commented May 1, 2015 at 22:00

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