There are some ways which cause an endless high CPU usage such as catching recursion exception. e.g. the following script in Python causes that problem:

def main():
    try:
        main()
    except:
        main()

main()

This is an obvious and simple example, but there might be some strange ways to arise such problems.

14 Answers 14

JavaScript

Even JavaScript beginners should understand the code below!

// JavaScript for Beginners
// Variables, for loops

// The line below will set a global variable called "x" to 90
// Note: never use this style of code. It is evil!
х = 90;

// The line below will set a local variable called "x" to 90
var x = 90;


for (var х=0; х<10; x++) {
  console.log('JS for beginners: this is iteration #' + х);
}

Warning

It produces an infinite loop
Don't run it in your browser unless you know how to kill the tab/process or restart the machine :)

How does it work?

There are two kinds of variable names in the code:
1. the normal 'x' which can be found on the keyboard
2. a cyrillic 'х': http://en.wikipedia.org/wiki/%D0%A5

  • 6
    That would be impossible to catch... Nice one. – Isiah Meadows Feb 23 '14 at 6:46
  • Reminds me of en.wikipedia.org/wiki/IDN_homograph_attack – aditsu Feb 23 '14 at 8:13
  • 1
    @aditsu In fact, I copied the cyrillic 'x' from that page :) – ComFreek Feb 23 '14 at 11:06
  • 1
    @impinball You can tell, because the SE code parser colors both xs differently. The second and fifth x are slightly darker than the others. – Timtech Feb 25 '14 at 0:05
  • @Timtech I'm sorry, but this method does not work anymore :P (I've set the language hint for the formatter to 'none'.) – ComFreek Feb 25 '14 at 15:59

Java

"Classic" example of backtracking hell in a backtracking regex engine:

class BacktrackingHell {
    public static void main(String args[]) {
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaab".matches("((a*)*)*"));
    }
}

If you are using Oracle's JVM, then you will run into the problem. Not sure for other JVMs.

If you see a regex engine that supports back-reference, then it is most likely to exhibit the same behavior.

  • Technically it's not endless, is it? – aditsu Feb 25 '14 at 3:21
  • @aditsu: Since the input is finite, as long as all branches are explored, the algorithm will halt. However, the complexity is so high that it takes very long for it to halt. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Feb 25 '14 at 5:11

JavaScript

var i = 0;
while (i < 10) {
  console.log("Hi #" + i + "!");
  // Let the user know we said hi and now     \
  // continue the loop                        \
  i++;
}

This looks rather harmless... (run at your own risk)

Spoiler:

Look at the commenting style. It will never get to 10 because of the escaped line breaks, which hold in comments. The problem would disappear completely if there was a line break after the final comment.

  • Nice use of escaping newlines. That is the closest thing to php's heredocs and nowdocs. – Ismael Miguel Feb 25 '14 at 0:05
  • This doesn't work on newer browsers, which don't recognise line continuations in comments. – Qantas 94 Heavy Feb 25 '14 at 9:31

Java

This may look like a silly but harmless program that should finish in an instant. However, appearances can be deceiving...

public class Cpu {
    public static void main(final String... args) {
        // let's print a bunch of empty lines
        int i = 0; // the loop counter
        while (i < 10) {
            // the unicode representation of a line feed is \u000A  /*/// loop start
            char c = 0x000A;
            System.out.print(c); // print the line feed
            i++; // increment and repeat  /*/// loop end
        }
    }
}

And another solution:

public class Cpu2 {
    public static void main(final String... args) {
        // now let's add the numbers from 0 to 255
        int sum = 0;
        for (byte i = 0; i < 255; i++) {
            sum += i;
        }
        System.out.println("The sum is: " + sum);
    }
}

Spoilers:

1. The "\u000A" inside the comment generates an actual line break in the source code, so all the instructions in the loop are commented out. Without the "\u000A" (or even without the backslash before "u"), the loop would just run 10 times and finish.
2. The 'byte' type is signed, so 'i' never reaches 255, but wraps around from 127 to -128

  • Is it the String args... that crashes it? – Isiah Meadows Feb 23 '14 at 6:48
  • The second one has an implicit cast, if I'm reading it properly. If not, then I would be surprised if it compiles. – Isiah Meadows Feb 23 '14 at 6:51
  • @impinball there is no String args... and no crash. Both programs compile and run with no errors and no warnings. – aditsu Feb 23 '14 at 7:41
  • Ok. Then I'm lost. – Isiah Meadows Feb 23 '14 at 7:47
  • The first has the contents of the loop commented out. That's why there – Isiah Meadows Feb 23 '14 at 7:50

C++

Try calculating the first 100 weird numbers by brute-force:

#include<iostream>
#include<vector>
using namespace std;

vector<int> divisors(int i) {

    vector<int> divs;
    for(int k = 1; k < i; k++)
        if(i%k==0)
            divs.push_back(k);
    return divs;
}

bool u(vector<int>::const_iterator vi, vector<int>::const_iterator end, int s) {

    if(s == 0) return 0;
    if(vi == end) return 1;
    return u(vi + 1, end, s - *vi) & u(vi + 1, end, s);
}

bool t(vector<int>&d, int i) {

    bool b = u(d.begin(), d.end(), i);
    if(b) cout<< i << endl;
    return b;
}

int main() {

    vector<int> divs;
    int n;
    cin>>n;

    for(int i = 2, j = 0; j < n; i++) {
        divs = divisors(i);

        int sum_divs = 0;
        for(int k = 0; k < divs.size(); k++)
            sum_divs += divs[k];

        if(sum_divs > i)
            if(t(divs, i))
                j++;
    }
}

I think you will find your CPU usage will spike, although it may not crash your computer.

It's the same solution I used in this question, but this time it's 100% fair.

Bash, 12 bytes

:(){ :|:&};:

As found on Wikipedia.

WARNING: harmful code, don't run it on your computer!

It produces an endless 100% CPU load (until system crashes, but there's nowhere stated that it mustn't be harmful!);

  • Your answer actually has a slight error: stackoverflow.com/questions/21186724/… – shiona Feb 22 '14 at 14:05
  • Drop the one space and it works in zsh ;-) – Isiah Meadows Feb 23 '14 at 6:46
  • As @shiona pointed out, without the space it won't work in Bash :P – Vereos Feb 23 '14 at 11:38
  • 1
    So I opened top in a second tab and ran this. It didn't actually generate any CPU load. Not even a single percent on my system. I suspect this is precisely because of the process limit. – Dennis Feb 23 '14 at 14:03

Vodoo in java

public class W
{
    public static void main(String[]a)
    {
        int o=0,о=o;
        while(o<a.length)
        {
            System.out.println(a[o]);
            о++;
        }
    }
}

cyrillic letters work in java, too :P that o=o isnt a o=o but 2 variables

EcmaScript 6:

z=z=>{while(1)z()};_=i=>(i+=1,i-=1,i++,i--,--i,++i,i<<=2,i>>=2,i+=0|Math.round(1+Math.random())&1|0,z(x=>setInterval(x=>z(x=>new Worker('data:text/javascript,'+_.toSource()),5))));setInterval(x=>z(x=>_(...Array(i=9e3).map((x,z)=>z*3/2*2/4*4e2>>2<<2))),5)

This doesn't always use 100% of the CPU, but at least with Firefox it has the added bonus that Firefox keeps using up more and more memory, the whole interface locks up and the only way to stop it is to kill Firefox.

BASH

This is a simple bash script and i'm sure it will be down voted for not being "strange" enough, but i found this fun. It's not elegant and it's not some fancy way to do it but it does the job in a fun way. Plus i have not seen anyone attempt to eat CPU usage by hashing out the sha256sum recently. This pipes its output to the file "~/junk" and thus eats up diskspace too (just for the giggles). It spawns itself over and over again. crashed my machine shortly after starting it.

THIS CODE IS DANGEROUS

Enjoy!

Name it songthatneverends.sh

#!/bin/bash
x=1
exec 1> ~/junk 2>&1

        while [ $x -le 1 ]
                do
                        song="This is the song that never ends, yes it goes on and on my friend. Some people started singing it, not knowing what it was, and they'll continue singing it forever just because..."
                        echo $song
                        $x"_"$song | sha256sum
                        x= $(( $x - 1 ))
                        sh songthatneverends.sh
                done
  • No part of this script does what it's intended to. 1. exec 1> ~/junk 2>&1 truncates the junk file. It never gets bigger than a few hundred bytes. 2. $x"_"$song produces an error, since the command 1_This does not exist. 3. x= $(( $x - 1 )) produces another error. Because of the space, the variable x gets set to the empty string before executing -1. 4. Because of the process limit, it doesn't actually generate any CPU load. Not even a single percent on my system. – Dennis Feb 23 '14 at 14:01

Ruby

Evals itself until it can't, then starts over.

begin;eval `cat spin.rb`;rescue;`ruby spin.rb`;end

Must be in a file named "spin.rb"

CMD 12 bytes (counting the important newline):

:a
a&goto a

This works because it has to look for the command a, and it has to spend time to produce an error message.

Then it goes to a: and repeats!

The newline is IMPORTANT and counts as 2 bytes under windows.

Since this is a Windows solution, the byte count has to (unfortunately) be made in Windows' way.

To stop it, close the window or press +c

DOS Batch

%0|%0

This is actually another way to code the fork bomb.

Equivalent in POSIX

$0|$0

Spoiler:

It runs the script itself, and attempts to pipe the output to the same script. Another way to write an endless loop of this is simply %0 or $0. The difference is that it doesn't nearly as much strain the CPU because it is simple recursion.

  • I totally used this as a golf for a similar question. – Isiah Meadows Feb 24 '14 at 16:37

Javascript:

(function(a){a=arguments.callee;try{a();}catch(e){a();}})();

How does this work?

This runs itself until it reaches the maximum recursion level. When this happens, the last function exits and runs itself again!

On my CPU, I got all 4 cores around 10-40%, using Opera 12.16.

To use it, simply press F12 on your keyboard, paste this in the console and done!

To stop, close the console.

C#

using System;
using System.Threading;

// without a program, we wouldn't have much, would we?
class Program
{
    // somehow, houdini always gets out of his locks
    static Guid houdini = Guid.NewGuid();

    // this is the main part
    static void Main()
    {
        // let's make some threads
        Thread[] threads = new Thread[20];
        // all of them
        for (int i = 0; i < threads.Length; i++)
        {
            // new threads are always better than stale ones
            threads[i] = new Thread(DoThing);
            // started threads are better than stopped ones
            threads[i].Start();
        }
    }

    // this does the thing
    static void DoThing()
    {
        // this does it lots of times
        while (true)
        {
            // this lock appears to limit CPU usage
            lock ((object)houdini)
            {
                // this line indicates I cannot think of anything clever to put here
                Thread.SpinWait(1000000);
            }
        }
    }
}

Spoiler:

lock ((object)houdini) creates a new reference to houdini and locks on that, so each lock gets a different reference, and the locks do not affect the other threads. This is why you should never use a value type for locking.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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