Weirdest way to produce a stack overflow

146

49

As a programmer you certainly know the error of a stack overflow due to an obvious recursion. But there are certainly many weird and unusual ways to get your favourite language to spit that error out.

Objectives:

  1. Must cause a stack overflow which is clearly visible on the error output.
  2. Not allowed to use an obvious recursion.

Examples of invalid programs:

// Invalid, direct obvious recursion.
methodA(){ methodA(); }
// Invalid, indirect, but obvious recursion.
methodA(){ methodB(); }
methodB(){ methodA(); }

The most creative ways are the best as this a . I.e, avoid boring obvious answers like this:

throw new StackOverflowError(); // Valid, but very boring and downvote-deserving.

Even though I accepted an answer now, adding more answers is still okay :)

masterX244

Posted 2014-02-17T08:57:34.803

Reputation: 3 942

Question was closed 2016-04-18T23:21:45.393

Here is the weirdest way to produce a StackOverflow. Get a time machine. Go back to 2008. Create a vote-based, community-run question-and-answer site about programming questions, where users can post their problems and get reliable results. Come back to your current time. Edit this post with the URL of your Q&A site. This should generate a StackOverflow. EDIT: I did it, here is my site: http://stackoverflow.com/

– ASCIIThenANSI – 2015-04-18T20:46:37.940

14I tend to produce by navigating to stackoverflow.com, though I have been known to query 'stack overflow' on my search engine of choice. – OJFord – 2014-02-17T13:19:21.613

It's too bad http://mailinator.blogspot.no/2009/06/beautiful-race-condition.html is just an infinite loop.

– Taemyr – 2014-02-17T14:35:08.277

1

There are many good (and short!) answers here: http://codegolf.stackexchange.com/questions/9359/shortest-program-that-throws-stackoverflow-error. I hope nobody will copy those answers.

– VisioN – 2014-02-17T15:51:59.403

1@JasonC You don't need to advertise your posts on this question with a comment. The OP owner will get a notification, and anyone who would upvote or such will find the answer without needing to read your comment. – Justin – 2014-02-18T04:14:51.967

@Quincunx Sure; sorry. – Jason C – 2014-02-18T04:41:23.470

21Use Internet Explorer. A sure way to catch one :) – asgoth – 2014-02-18T17:48:19.697

@asgoth explain plz – masterX244 – 2014-02-18T17:53:18.710

1@masterX244 I mean, IE can produce javascript errors (e.g. stackoverflow at line 0), while the code runs fine in other browsers. My comment was meant to be sarcastic. Sorry if it failed. – asgoth – 2014-02-18T18:38:08.907

didnt knew that one thats why i asked @asgoth avoiding Internet Exploder since multiple years so the bugs didnt fgound a way into my memory – masterX244 – 2014-02-18T18:39:30.767

Hey does it have to compile? I have given an example of one that would overflow, but compilers will refuse to compile it because the behavior is never intended, not because it is semantically wrong. (C++ - constructor to construct temporary to pass to constructor causes infinite loop at runtime) – Alec Teal – 2014-02-18T20:19:35.277

post cause some compilers could accept it; (like the TeX example which relies on certain versions – masterX244 – 2014-02-18T20:20:33.530

64The weirdest way to produce a stack overflow is to post a popularity-contest on codegolf.stackexchange.com asking for people to post the weirdest way to produce a stack overflow. The responders, in testing their solutions to the question, will produce a stack overflow. I haven't tested it though, so I can't be sure it works (which is why I didn't post it as an answer). – Tim Seguine – 2014-02-18T20:32:59.457

3

I'm partial to this method: http://www.joelonsoftware.com/items/2008/09/15.html

– robert – 2014-02-19T13:10:21.493

@TimSeguine - that sure sound like recursion to me! – TheDoctor – 2014-02-20T02:11:58.240

2

#Quine# This is only an idea (one specific implementation in Java can be found here). A quine is a program that produces it's own code. If you take it a step further, you can make the code be saved to file and compiled during run time, then executed. This will not cause a classic StackOverFlow error, but a (much more risky...) disk memory overflow.

– Elist – 2014-02-19T15:44:14.103

I'm presuming that the goal is to cause an actual stack overflow, rather than to simply throw a StackOverflowError or whatever your language calls it. – keshlam – 2014-02-21T21:20:04.883

11Drive a Toyota (Hey, wait a minute, my car is a Toyota...) – r3mainer – 2014-02-22T01:08:03.487

I used to have a program bug that called a super-method of an overridden method by accident, causing a stack-overflow by the EventDispatcher thread, but I can't remember where nor reproduce it. – Mark Jeronimus – 2014-02-26T09:34:58.747

Answers

224

Python

import sys
sys.setrecursionlimit(1)

This will cause the interpreter to fail immediately:

$ cat test.py
import sys
sys.setrecursionlimit(1)
$ python test.py
Exception RuntimeError: 'maximum recursion depth exceeded' in <function _remove at 0x10e947b18> ignored
Exception RuntimeError: 'maximum recursion depth exceeded' in <function _remove at 0x10e8f6050> ignored
$ 

Instead of using recursion, it just shrinks the stack so it will overflow immediately.

marinus

Posted 2014-02-17T08:57:34.803

Reputation: 30 224

1We've heard the old joke, the optimist sees a glass half-full, the pessimist sees a glass half-empty, and the programmer shrinks the glass so it gives off a glass overflow error. – ASCIIThenANSI – 2015-04-11T03:01:17.280

When this code is executed in an interactive Python prompt, the interpreter is unable to even give an explanation for the error. It just gives RuntimeError no matter what you enter, even a blank line. If the recursion limit is set to 2, all statements still fail (including blank lines), but it'll give RuntimeError: maximum recursion limit exceeded. If the recursion limit is set to 3, anything that indirectly calls a function will fail but a traceback is generated (and blank lines no longer generate errors). – bwDraco – 2015-04-30T03:21:51.660

3I do love that :D – Kiwy – 2014-02-17T13:35:40.180

1.......... cute – Carl Smith – 2014-02-17T21:25:03.503

12Cute, but not quite what the original question was aiming for in my opinion. – Nit – 2014-02-17T22:01:35.203

12@Nit I don't see the problem. What about this solution is unsatisfactory? – SimonT – 2014-02-18T06:08:43.410

@Nit its not the usualy way of spamming stack :) – masterX244 – 2014-02-18T11:45:03.327

17@masterX244 Yes, the whole point of the question is "don't do it the usual way". – Plutor – 2014-02-18T12:58:55.713

24@Plutor do you usually set up a StackOverFlow on purpose ? – Kiwy – 2014-02-18T13:54:24.330

15

This was only mildly clever the first time it was posted.

– primo – 2014-02-20T10:55:15.957

1@primo 185 upvotes disagree with you. :) – asteri – 2014-05-13T13:25:36.490

3@JeffGohlke As a matter of etiquette, answers which are not original to the poster, or have been posted elsewhere on this site verbatim, should be marked as community wiki. Also, this question was posted just after a surge of activity from ~600 visits per day, to over 4000 per day, which I believe thoroughly explains the low quality of the highest voted answers. – primo – 2014-05-13T14:12:11.990

189

Python

import webbrowser
webbrowser.open("http://stackoverflow.com/")

TheDoctor

Posted 2014-02-17T08:57:34.803

Reputation: 7 793

7Fantastic. Nice and elegant. – James Webster – 2014-02-18T16:08:18.773

103Much literal. Very answer. – Tim Seguine – 2014-02-18T20:58:43.917

2I don't see the recursion – copy – 2014-02-19T02:16:13.563

2@copy Recursion ain't needed. Ya just need ta make a stackoverflow. – Justin – 2014-02-19T04:08:42.160

47Well, this shows a Stack Overflow, but to produce one, this only works if it's Jeff Atwood or Joel Spolsky executing it. – Mechanical snail – 2014-02-20T00:22:36.000

10@TimSeguine Wow. – Sean Allred – 2014-02-20T04:15:11.663

9Not an answer as it's not in the error output. – Pierre Arlaud – 2014-02-20T12:40:39.083

My face when I saw this answer. I was actually thinking the same thing when I clicked it from Hot Network Questions. – NobleUplift – 2014-02-20T18:14:18.897

2@TimSeguine I up-votted your comment then accidentally clicked again and it undid my up vote and apparently if you undo an up vote it won't let you re-upvote after (even after waiting the 5 seconds)... I would go complain on META but I'm too lazy... you should be able to #Meta in comments and it auto-generates a post on META :D – Albert Renshaw – 2014-02-21T04:31:27.590

4@Mechanicalsnail produce: Show or provide (something) for consideration, inspection, or use. E.g., "he produced a sheet of paper from his pocket". Synonyms: present, offer, provide, furnish, advance, put forward, bring forward, come up with. Have I sufficiently swayed you to accept even the technical/pedantic correctness of this answer, or should I produce more evidence? – Will – 2014-02-21T04:46:24.420

2I'm voting this up because I didn't know about the webbrowser module, it's awesome. – OregonTrail – 2014-02-22T00:20:55.437

I don't want to see your production code, if this is supposed to be the weirdest way to produce a stackoverflow – sehe – 2014-02-24T09:11:06.587

@AlbertRenshaw I believe you can recast your upvote if somebody edits the answer. – Jason C – 2014-02-25T16:46:21.397

@AlbertRenshaw Maybe you should write a Meta post about using #Meta to auto generate a Meta post. But, I guess you're too lazy until they implement this feature. At which time you requesting it would be moot – Cruncher – 2014-02-25T17:39:36.817

@AlbertRenshaw And you clicked OK to the JavaScript dialog that warns you that you will not be able to upvote it again? – Tortoise – 2014-06-02T01:30:28.847

1@Tortoise Did not exist at the time. But even if it did, as with most dialogues, 90% of people will click okay without reading it. For this very reason, dialogue consequences should never be permanent. – Albert Renshaw – 2014-06-02T22:09:21.177

@AlbertRenshaw Oh wow, that was a three-month-old post. I dug too deep. – Tortoise – 2014-06-03T02:23:22.640

131

C / Linux 32bit

void g(void *p){
        void *a[1];
        a[2]=p-5;
}
void f(){
        void *a[1];
        g(a[2]);
}
main(){
        f();
        return 0;
}

Works by overwriting the return address, So g returns to the point in main before calling f. Will work for any platform where return addresses are on the stack, but may require tweaks.

Of course, writing outside of an array is undefined behavior, and you have no guarantee that it will cause a stack overflow rather than, say, paint your mustache blue. Details of platform, compiler and compilation flags may make a big difference.

ugoren

Posted 2014-02-17T08:57:34.803

Reputation: 16 527

1Wouldn't this produce a segfault? – 11684 – 2014-02-17T14:01:41.787

4+1 for the weird stack manipulation and absolutely no recursion! – RSFalcon7 – 2014-02-17T14:39:53.547

6@11684, It's undefined behavior, so in general it could crash. On 32bit Linux (that I tested on), it writes outside the array, overwriting the return address, and doesn't crash until the stack overflows. – ugoren – 2014-02-17T14:45:58.973

I get a segmentation fault (@11684) when i try to run this. (gcc 4.7.3, Xubuntu 13.10) – klingt.net – 2014-02-17T16:53:00.140

@klingt.net, A stack overflow causes a segmentation fault. But it might fail if you use 64bit. – ugoren – 2014-02-17T18:10:22.043

1Note that gcc would optimize it away at -O2 and higher. – devnull – 2014-02-17T18:39:09.110

1@devnull, I guess I need to emphasize "undefined behavior" in the post. – ugoren – 2014-02-17T20:11:23.067

@ugoren Fair enough. Neither have I downvoted your answer, nor did I say that it's wrong. I simply stated that it (or as you'd prefer, the undefined behavior) wouldn't work with -O2 or higher. – devnull – 2014-02-17T20:14:26.327

46"Paint your moustache blue" -> That line had me. – Aneesh Dogra – 2014-02-17T21:22:00.917

@ugoren, you are right, my fault.

– klingt.net – 2014-02-17T21:25:02.747

2Wow. This is fantastically obfuscated. – MirroredFate – 2014-02-17T23:59:18.363

@11684 It will cause a seg fault due to stack overflow but not necessarily a seg fault due to a direct access violation, as long as a[2] still points into the address space of the process (which, in a working case of this program, it does). – Jason C – 2014-02-18T23:33:05.423

I think changing into this will work on x64 Linux: http://pastebin.com/p4KEqSmS

– Alvin Wong – 2014-02-19T10:22:56.853

@AneeshDogra Heck, it could kill your family! – Cole Johnson – 2014-02-21T04:15:17.593

108

JavaScript / DOM

with (document.body) {
    addEventListener('DOMSubtreeModified', function() {
        appendChild(firstChild);
    }, false);

    title = 'Kill me!';
}

If you want to kill your browser try that out in the console.

VisioN

Posted 2014-02-17T08:57:34.803

Reputation: 4 490

Isn't this recursion though? It'll just keep on repeating the same function. – xji – 2015-11-18T04:44:22.087

53I'm sure you deserve more +1 votes, but sadly people tried this before voting.... lol – Reactgular – 2014-02-18T23:06:12.783

5Well, that was effective. I couldn't even get my task manager open to kill it. – primo – 2014-02-20T14:54:18.367

1Use Chrome, close tab. Problem solved. – Cole Johnson – 2014-02-21T04:19:14.253

1`with (document.body) { addEventListener('DOMSubtreeModified', function() { appendChild(firstChild); }, false);

title = 'Kill me!';

} 15:43:43.642 TypeError: can't convert undefined to object` – Brian Minton – 2014-02-21T20:44:03.897

1Damn My Firefox was hanged – Farhad – 2014-02-24T10:14:46.293

My Firefox wokrs fine with this code, just shown box saying "The script works long, continue?" – PeterM – 2014-03-03T11:12:11.347

91

Java

Saw something like this somewhere around here:

Edit: Found where I saw it: Joe K's answer to Shortest program that throws StackOverflow Error

public class A {
    String val;
    public String toString() {
        return val + this;
    }

    public static void main(String[] args) {
        System.out.println(new A());
    }
}

That can confuse some Java beginners. It simply hides the recursive call. val + this becomes val + this.toString() because val is a String.

See it run here: http://ideone.com/Z0sXiD

Justin

Posted 2014-02-17T08:57:34.803

Reputation: 19 757

30Actually, it does new StringBuilder().append(val).append("").append(this).toString(), and the last append calls String.valueOf(...), which in turn calls toString. This makes your Stack trace a bit varied (three methods in there). – Paŭlo Ebermann – 2014-02-17T14:13:18.127

2@PaŭloEbermann Yeah, that is correct. However, it is much easier to say that it becomes "" + this.toString(). – Justin – 2014-02-18T03:35:12.437

2I think the + "" + might tip people off, as it looks useless at first glance. String val; and return val + this; might be marginally sneakier – Cruncher – 2014-02-18T21:45:44.040

@Cruncher not at all. If you are a Java coder, you would know that the easy way of concatenating an int to a string during ""-String construction is with the + "" – Justin – 2014-02-19T01:20:49.687

@quincunx actually in java int+string works. The purpose in this case is because int + Object is undefined. To get the implicit toString call you need to concat object with a string. – Cruncher – 2014-02-19T12:14:25.070

In a real world application I would prefer val+this.toString(); explicit is always better – Cruncher – 2014-02-19T12:17:12.940

5In a real world application I would prefer to avoid infinite recursion and stack overflow errors – jon_darkstar – 2014-02-23T15:32:11.833

77

C

Quite easy:

int main()
{
    int large[10000000] = {0};
    return 0;
}

Shahbaz

Posted 2014-02-17T08:57:34.803

Reputation: 870

10+1 for non obvious! Despite it is very system dependent (an ulimit -s unlimited in the shell solves this in linux) – RSFalcon7 – 2014-02-17T14:57:07.880

4@RSFalcon7, thanks for the +1, but to me this was actually the most obvious!! – Shahbaz – 2014-02-17T18:39:24.750

Is this just 0ing the stack? How does that result in recursion? – Cruncher – 2014-02-18T17:48:07.807

14@Cruncher: It doesn't result in recursion. The problem given was to blow the stack. On many operating systems the stack is of fixed size, and far smaller than ten million ints, so this blows the stack. – Eric Lippert – 2014-02-18T17:58:28.527

Do we get the requested "stack overflow" error message for this one? Or rather some out-of-memory when trying to allocate the array? – JimmyB – 2014-02-19T13:31:51.047

2@HannoBinder, In Linux where I tested, you don't get a stack overflow error. You get a segmentation fault, since overflowing the stack results in access to unowned segments. I'm not sure if stack overflow error even exists in Linux, since an infinite recursive function call also gives out a segmentation fault. – Shahbaz – 2014-02-19T13:33:22.850

Ok, thanks for the explanation :) – JimmyB – 2014-02-19T13:44:06.440

I'm not entirely sure, but I think you can reduce that code by replacing 10000000 with 9e9. – Ismael Miguel – 2014-02-20T00:30:37.610

@IsmaelMiguel, no, because 9e9 is of type double. Although (int)9e9 would work. – Shahbaz – 2014-02-20T12:12:31.283

Then it's not worth to change it in the answer. It would be sweet if you could do 9e9 like in PHP. – Ismael Miguel – 2014-02-20T12:15:38.117

9**9 is pretty large number too – gnibbler – 2014-02-21T12:09:50.740

1But 9**9 isn't C. – David Conrad – 2014-02-23T03:37:16.430

3~0u is a pretty large number in C. – Vortico – 2014-02-23T20:20:17.983

@Vortico, yes that could also be used. Although it's not necessarily a pretty large number in C, but rather on 32-bit or 64-bit architectures. – Shahbaz – 2014-02-24T12:35:17.760

63

Non-recursive stack overflow in C

Calling convention mismatch.

typedef void __stdcall (* ptr) (int);

void __cdecl hello (int x) { }

void main () {
  ptr goodbye = (ptr)&hello;
  while (1) 
    goodbye(0);
}

Compile with gcc -O0.

__cdecl functions expect the caller to clean up the stack, and __stdcall expects the callee to do it, so by calling through the typecast function pointer, the cleanup is never done -- main pushes the parameter onto the stack for each call but nothing pops it and ultimately the stack fills.

Jason C

Posted 2014-02-17T08:57:34.803

Reputation: 6 253

2nice way of spamming the stack :P – masterX244 – 2014-02-18T08:23:30.557

62

I was frustrated by the fact that java 7 and java 8 are immune to my evil code in my previous answer. So I decided that a patch for that was necessary.

Success! I made printStackTrace() throw a StackOverflowError. printStackTrace() is commonly used for debugging and logging and no one reasonably suspects that it could be dangerous. It is not hard to see that this code could be abused to create some serious security issues:

public class StillMoreEvilThanMyPreviousOne {
    public static void main(String[] args) {
        try {
            evilMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void evilMethod() throws Exception {
        throw new EvilException();
    }

    public static class EvilException extends Exception {
        @Override
        public Throwable getCause() {
            return new EvilException();
        }
    }
}

Some people may think that this is an obvious recursion. It is not. The EvilException constructor does not calls the getCause() method, so that exception can actually be thrown safely after all. Calling the getCause() method will not result in a StackOverflowError either. The recursion is inside JDK's normally-unsuspected printStackTrace() behaviour and whatever 3rd party library for debugging and logging that are used to inspect the exception. Further, it is likely that the place where the exception is thrown is very far from the place where it is handled.

Anyway, here is a code that does throw a StackOverflowError and contains no recursive method calls after all. The StackOverflowError happens outside the main method, in JDK's UncaughtExceptionHandler:

public class StillMoreEvilThanMyPreviousOneVersion2 {
    public static void main(String[] args) {
        evilMethod();
    }

    private static void evilMethod() {
        throw new EvilException();
    }

    public static class EvilException extends RuntimeException {
        @Override
        public Throwable getCause() {
            return new EvilException();
        }
    }
}
Exception: java.lang.StackOverflowError thrown from the UncaughtExceptionHandler in thread "main"

Victor Stafusa

Posted 2014-02-17T08:57:34.803

Reputation: 8 612

2:D and now with a cross java version stackoverflow compliant method. Evil bastard ! :D – Kiwy – 2014-02-17T13:32:55.307

9I am inclined to consider the recursion in this case obvious. – Taemyr – 2014-02-17T14:34:07.023

@Taemyr See my edit – Victor Stafusa – 2014-02-17T15:57:54.757

@Victor Looks the same to me…EvilExceptions make new EvilExceptions when you call getCause(). – Blacklight Shining – 2014-02-17T16:15:12.723

1@BlacklightShining Calling the getCause() method does not results in StackOverflowError. It is relying in the fact that there is a JDK's code which is recursively calling the getCause() method. – Victor Stafusa – 2014-02-17T16:17:47.260

And people who thinks that there is an obvious recursion. Can you show me, in my second code, which lines do an obvious recursion? – Victor Stafusa – 2014-02-17T16:22:02.157

@Victor Why would getCause() ever return a new instance of the exception class that's being defined? It doesn't seem useful at all, unlike, say, overriding stdout and stderr or printing a stack trace on exception.

– Blacklight Shining – 2014-02-17T17:55:51.040

@BlacklightShining I didn't say that it is useful. I just said that it is no recursion. If the constructor actually called getCause() it would be recursion, but it doesn't. – Victor Stafusa – 2014-02-17T17:58:11.793

I don't think the edit makes the recursion any less obvious. The fact that you make a valid program cause an error in the JDK outside of your code is cool. The fact that people are expecting getCause to be the thing that is recursing is perhaps a strong argument that the recursion is nonobvious. – Taemyr – 2014-02-18T10:15:03.683

Interesting. This doesn't seem to overflow when using a checked exception and printing the stacktrace. Perhaps the error stems from the JDK being less rigorous with unchecked exceptions? – Cruncher – 2014-02-18T17:46:40.267

@Cruncher I tested this using java 1.8.0-b109 (early access, a bit old but just a bit) and got the StackOverflowError regardless of if I made EvilException to extends Exception, RuntimeException, Error or even directly from Throwable in both forms posted in this answer. Which JDK/JRE version are you using? – Victor Stafusa – 2014-02-18T18:02:31.727

@Victor 7. Nevermind though. It never printed something like Exception: java.lang.StackOverflowError thrown from the UncaughtExceptionHandler in thread "main" at the end, but it still throws a stackoverflow with a long stack trace. – Cruncher – 2014-02-18T18:18:37.527

2I thought you could simplify this by changing the body of getCause to just return this; but apparently Java is too clever for that. It notices that it is a "CIRCULAR REFERENCE". – David Conrad – 2014-02-23T03:56:32.290

1I did not get a StackOverflowError because the OpenBSD 5.5 package of jdk-1.7.0.21p2v0 has a bug. It doesn't throw StackOverflowError. It hits SIGSEGV and dumps core. – kernigh – 2014-05-12T23:00:41.933

62

JavaScript

window.toString = String.toLocaleString;
+this;

Ryan Cavanaugh

Posted 2014-02-17T08:57:34.803

Reputation: 720

5This one is underappreciated. – Ry- – 2014-02-20T02:11:29.553

1What does +this do? – NobleUplift – 2014-02-20T19:24:14.357

8Unary + invokes the ToNumber abstract operation. That uses the ToPrimitive operation with a hint type of number. ToPrimitive on an Object uses the [[DefaultValue]] internal method, which when passed a number hint, first checks to see if the valueOf() method exists and returns a primitive. window.valueOf() returns an object, so instead [[DefaultValue]] returns the result of calling toString(). The first thing window.toString does (now that it's toLocaleString) is invoke toString on 'this'. Repeat. – Ryan Cavanaugh – 2014-02-20T19:40:46.500

It doesn't work anymore (Firefox 25 returns NaN, Chrome throws error - "Too much recursion"). – Ginden – 2014-02-22T15:14:38.003

3If Chrome throws an error, 'Too much recursion', then it does work on Chrome, right? The stack overflows, and that's how Chrome delivers a stack overflow exception. – David Conrad – 2014-02-23T04:02:47.917

4You should use +{toString:"".toLocaleString} :-) – Bergi – 2014-02-24T04:26:23.027

57

Linux x86 NASM Assembly

section .data
    helloStr:     db 'Hello world!',10 ; Define our string
    helloStrLen:  equ $-helloStr       ; Define the length of our string

section .text
    global _start

    doExit:
        mov eax,1 ; Exit is syscall 1
        mov ebx,0 ; Exit status for success
        int 80h   ; Execute syscall

    printHello:
        mov eax,4           ; Write syscall is No. 4
        mov ebx,1           ; File descriptor 1, stdout
        mov ecx,helloStr    ; Our hello string
        mov edx,helloStrLen ; The length of our hello string
        int 80h             ; execute the syscall

    _start:
        call printHello ; Print "Hello World!" once
        call doExit     ; Exit afterwards

Spoiler:

Forgetting to return from printHello, so we jump right into _start again.

Michael Ehrenreich

Posted 2014-02-17T08:57:34.803

Reputation: 799

78In assembly, nothing is obvious. – 11684 – 2014-02-17T14:00:39.813

21@11684: I find the opposite to be true: in assembly, everything is obvious because nobody can use abstractions to hide what their code is really doing. – Mason Wheeler – 2014-02-17T20:06:01.650

3This is brilliant for its simplicity and elegance. – haneefmubarak – 2014-02-17T20:13:23.040

11

@MasonWheeler: I prefer to say that everything is visible instead of obvious... For a nice way to see the difference between visible and obvious, I love to refer to http://underhanded.xcott.com

– Olivier Dulac – 2014-02-18T10:13:47.770

1@11684 I don't know, it's pretty obvious that this is classic recursion; the explanation of "if you forget to ..." is a bit sleight-of-hand. – Jason C – 2014-02-18T23:25:54.457

1

@MasonWheeler I see your "nobody can use abstractions to hide what their code is really doing" and raise you http://en.wikipedia.org/wiki/Polymorphic_code. Back before anti-virus software was so prevalent and comprehensive; self-modifying assembler programs (and the study of them) were all the rage.

– Jason C – 2014-02-18T23:27:51.903

2I remember my frequent mistakes of forgetting ret – Ruslan – 2014-02-19T08:54:39.600

48

C++ at compile time

template <unsigned N>
struct S : S<N-1> {};

template <>
struct S<0> {};

template
struct S<-1>;
$ g++ -c test.cc -ftemplate-depth=40000
g++: internal compiler error: Segmentation fault (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See  for instructions.

There is no recursion this source file, not one of the classes has itself as a base class, not even indirectly. (In C++, in a template class like this, S<1> and S<2> are completely distinct classes.) The segmentation fault is due to stack overflow after recursion in the compiler.

hvd

Posted 2014-02-17T08:57:34.803

Reputation: 3 664

7I confess I would have called this an obvious recursion in your metaprogram. – None – 2014-02-17T16:59:01.430

2GCC detects recursion and stops gracefully this side (4.8 and above seem to be fine) – Alec Teal – 2014-02-17T18:39:49.377

@AlecTeal It detects an excessively large template instantiation depth. It doesn't call it recursion, because it isn't, other than in GCC's own source code. :) But you have a larger stack than I did on the system I tested this on. If you use a larger maximum (try 200000, or perhaps even 2000000), you'll get the same segmentation fault. – hvd – 2014-02-17T18:45:20.460

2template <typename T> auto foo(T t) -> decltype(foo(t)); decltype(foo(0)) x; is a bit shorter. – Casey – 2014-02-17T21:13:59.363

1@Casey Nice idea! I'm surprised that that fails, though. In the trailing return type, the function being declared isn't available yet, unless later found by ADL, but int has no associated namespace. If I try it with a struct S, I do expect it to fail, and unlike the version with int it also causes a segfault in clang. – hvd – 2014-02-17T21:37:14.063

2

@hvd It seems to be exploiting a bug in GCC. clang catches the erroneous usage - which I assume you are already aware of - but it makes my GCC spew almost 2 megabytes of error messages.

– Casey – 2014-02-17T22:35:48.443

+1 for stackoverflow @compiler; btw java can be stackoverflown in compiler, too :P – masterX244 – 2014-02-18T11:44:29.357

4

+1 for meta stack overflow :p

– Aschratt – 2014-02-21T10:12:19.883

Still crashes the compiler as of GCC 4.9.1 (MinGW-w64): "cc1plus.exe has stopped working". Visual C++ gives main.cpp(2): fatal error C1202: recursive type or function dependency context too complex. – bwDraco – 2014-10-02T03:02:26.677

45

Bash (Danger Alert)

while true
do 
  mkdir x
  cd x
done

Strictly speaking, that will not directly stack overflow, but generates what may be labelled as "a persistent stack-over-flow generating situation": when you run this until your disk is full, and want to remove the mess with "rm -rf x", that one is hit.

It does not happen on all systems, though. Some are more robust than others.

Big danger WARNING:

some systems handle this very badly and you may have a very hard time cleaning up (because "rm -rf" itself will run into a recusion problem). You may have to write a similar script to cleanup.

Better try this in a scratch VM if not sure.

PS: the same applies, of course, if programmed or done in a batch script.
PPS: it may be interresting to get a comment from you, how your particular system behaves...

blabla999

Posted 2014-02-17T08:57:34.803

Reputation: 1 869

as I wrote: on many systems, rm -rf tries to go down and is hit by one (maybe no longer, these days, with 64bit address space - but on smaller machines with a smaller stack, it may). Of course, there may also be "rm"-implementations around, which do it differently... – blabla999 – 2014-02-17T12:48:51.323

2Seems to me something like while cd x; do :; done; cd ..; while rmdir x; cd ..; done; should take care of this. – Blacklight Shining – 2014-02-17T15:29:06.920

You are absolutely right (that's what I meant with "similar script for cleanup"). However, once your disk (or quota) is full, you may even have a hard time logging in afterwards, as some systems used to deal with that situation badly. You'll have to get in as root and do the script (which is easy on those PCs of today, but was often hard in ancient times, when computers where used by more than one user). – blabla999 – 2014-02-18T10:57:46.720

funny, this gets more votes than the Smalltalk magic below (never thought that!) – blabla999 – 2014-02-18T11:55:51.723

someone tried this on Windows? – Display Name – 2014-02-21T07:52:31.543

On Windows paths can only be so long (~256 characters). – kinokijuf – 2014-02-22T17:17:24.597

Typically this will run until there are no iNodes left, not until the disk is full. – Rui Marques – 2014-02-24T16:28:13.210

This is harmless. I just tried (feb. 2014) with Linux 3.10.17 / bash 4.2.45 / ext4 (ext2fs 1.42.7) / coreutils 8.21 -- they are not that fragile – Ярослав Рахматуллин – 2014-03-04T17:38:50.530

Does not work with sh in OpenBSD 5.5-current. I used sh because bash was not installed. It soon went into an infinite loop printing mkdir: x: File exists and attack.sh[5]: cd /tmp/x/x/x/.../x - File name too long. I did rm -rf x and tried again with perl -e 'for(;;){mkdir"x";chdir"x"}'. After several minutes, this became an infinite loop printing /tmp: create/symlink failed, no inodes free. Command rm -rf x succeeded after about an hour. No stack overflow. – kernigh – 2014-05-13T01:26:10.013

43

Java

A nice one from Java Puzzlers. What does it print?

public class Reluctant {
    private Reluctant internalInstance = new Reluctant();

    public Reluctant() throws Exception {
        throw new Exception("I'm not coming out");
    }

    public static void main(String[] args) {
        try {
            Reluctant b = new Reluctant();
            System.out.println("Surprise!");
        } catch (Exception ex) {
            System.out.println("I told you so");
        }
    }
}

It actually fails with a StackOverflowError.

The exception in the constructor is just a red herring. This is what the book has to say about it:

When you invoke a constructor, the instance variable initializers run before the body of the constructor. In this case, the initializer for the variable internalInstance invokes the constructor recursively. That constructor, in turn, initializes its own internalInstance field by invoking the Reluctant constructor again and so on, ad infinitum. These recursive invocations cause a StackOverflowError before the constructor body ever gets a chance to execute. Because StackOverflowError is a subtype of Error rather than Exception, the catch clause in main doesn't catch it.

ntoskrnl

Posted 2014-02-17T08:57:34.803

Reputation: 857

41

LaTeX

\end\end

The input stack overflows because \end repeatedly expands itself in an infinite loop, as explained here.

TeX fails with a TeX capacity exceeded, sorry [input stack size=5000] or similar.

bwDraco

Posted 2014-02-17T08:57:34.803

Reputation: 571

1"TeX capacity exceeded, sorry" TeX is so polite when it fails. – Alex A. – 2015-04-30T03:08:34.150

1I was waiting for a TeX/LaTeX issue. Those things are more jarring than most - usually, I've forgotten that what I'm doing counts as programming when suddenly I've managed to write something that is infinitely recursive. – Ernir – 2014-02-20T09:38:56.113

40

BF

Will eventually overflow the stack, just depends how long the interpreter makes the stack...

+[>+]

Timtech

Posted 2014-02-17T08:57:34.803

Reputation: 12 038

5That code reminds me of game of life. – Adam Arold – 2014-02-18T01:23:17.190

10Strictly speaking, there is no stack in brainfuck. – fejesjoco – 2014-02-20T15:07:24.673

6@fejesjoco Tape, if you wish. – Timtech – 2014-02-20T15:31:40.097

32

On the Internet (used by billion people/day)

Redirects, HTTP status code: 301

For example, on the Dell support website (no offense, sorry Dell):

If you remove the support TAG from the URL then it goes into infinite redirects. In the following URL, ###### is any support TAG.

http://www.dell.com/support/drivers/uk/en/ukdhs1/ServiceTag/######?s=BSD&~ck=mn

I believe it's equivalent to a stack overflow.

codeSetter

Posted 2014-02-17T08:57:34.803

Reputation: 420

That awkward moment when the internet breaks itself. – ASCIIThenANSI – 2015-04-11T02:58:04.510

5nice way :) firefox tells that it redirects so the request cannot be resolved which is the stackoverflow rquivalent :) – masterX244 – 2014-02-17T16:13:20.607

3Note that the redirects are not infinite -- if you hit "Try Again" it adds a few more /Errors/'s to the URL and then stops after receiving HTTP 400 Bad Request. But this arguably makes for a better stack overflow than an infinite redirect does. – nandhp – 2014-02-17T22:15:56.130

@nandhp, I agree, but if you think a third world browser(not modern, IE etc..), They haven't got clue of this situation. – codeSetter – 2014-02-18T09:30:37.810

2

Here's how Wget responds here: http://pastebin.com/pPRktM1m

– bwDraco – 2014-02-19T20:37:37.003

1http://www.dell.com/support/drivers/uk/en/ukdhs1/ServiceTag/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/Errors/... – Vortico – 2014-02-23T20:26:58.980

32

C#, at compile time

There are a number of ways to cause the Microsoft C# compiler to blow its stack; any time you see an "expression is too complex to compile" error from the C# compiler that is almost certainly because the stack has blown.

The parser is recursive descent, so any sufficiently deeply nested language structures will blow the stack:

 class C { class C { class C { ....

The expression parser is pretty smart about eliminating recursions on the side that is commonly recursed on. Usually:

x = 1 + 1 + 1 + 1 + .... + 1;

which builds an enormously deep parse tree, will not blow the stack. But if you force the recursion to happen on the other side:

x = 1 + (1 + (1 + (1 + ....+ (1 + 1))))))))))))))))))))))))))))))))))))))))))...;

then the stack can be blown.

These have the inelegant property that the program is very large. It is also possible to make the semantic analyzer go into unbounded recursions with a small program because it is not smart enough to remove certain odd cycles in the type system. (Roslyn might improve this.)

public interface IN<in U> {}
public interface IC<X> : IN<IN<IC<IC<X>>>> {}
...
IC<double> bar = whatever;
IN<IC<string>> foo = bar;  // Is this assignment legal? 

I describe why this analysis goes into an infinite recursion here:

http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx

and for many more interesting examples you should read this paper:

http://research.microsoft.com/en-us/um/people/akenn/generics/FOOL2007.pdf

Eric Lippert

Posted 2014-02-17T08:57:34.803

Reputation: 2 805

2

The exact error message is fatal error CS1647: An expression is too long or complex to compile near (code). The documentation for this error message is here, and it's exactly as you say: "There was a stack overflow in the compiler processing your code."

– bwDraco – 2014-02-24T17:52:50.403

31

PHP

A stackoverflow done with looping elements only.

$a = array(&$a);
while (1) {
    foreach ($a as &$tmp) {
        $tmp = array($tmp, &$a);
    }
}

Explanation (hover to see the spoiler):

The program will segfault when the interpreter tries to garbage collect the $tmp array away (when reassigning $tmp here). Just because the array is too deep (self referencing) and then the garbage collector ends up in a recursion.

bwoebi

Posted 2014-02-17T08:57:34.803

Reputation: 1 721

16PHP's GC can't detect self-referential structures? Really?! Ouch. That is evil. – Peter C – 2014-02-18T07:19:03.710

1Yes, but it's not perfect. There's some reason why while (1) { $a = array(&$a); } or something similar just hits the memory limit… – bwoebi – 2014-02-18T10:28:29.683

yup, I think it's the same reason why PHP is not working properly regarding Object Oriented development either; (abstraction, inheritance etc.) – pythonian29033 – 2014-02-24T08:38:24.197

1@pythonian29033 care to elaborate? – vvondra – 2014-03-01T19:51:32.650

30

Java

I did the exact opposite – a program that should obviously throw a stack overflow error, but doesn't.

public class Evil {
    public static void main(String[] args) {
        recurse();
    }

    private static void recurse() {
        try {
            recurse();
        } finally {
            recurse();
        }
    }
}

Hint: the program runs in O(2n) time, and n is the size of the stack (usually 1024).

From Java Puzzlers #45:

Let's assume that our machine can execute 1010 calls per second and generate 1010 exceptions per second, which is quite generous by current standards. Under these assumptions, the program will terminate in about 1.7 × 10291 years. To put this in perspective, the lifetime of our sun is estimated at 1010 years, so it is a safe bet that none of us will be around to see this program terminate. Although it isn't an infinite loop, it might as well be.

ntoskrnl

Posted 2014-02-17T08:57:34.803

Reputation: 857

3Obvious recursion ... not very interesting. – Kami – 2014-02-17T14:34:59.567

5@Kami Have you tried it? Did you actually get a StackOverflowError? It seems obvious, but it's not. – ntoskrnl – 2014-02-17T14:49:37.543

Just because an exception gets caught doesn't mean it was never thrown. This program throws a stack overflow exception after time O(n) – CodesInChaos – 2014-02-17T15:40:15.520

1@CodesInChaos Okay, so I double-checked this, and the correct version uses finally rather than catch, and the running time is O(2^n). Answer updated. – ntoskrnl – 2014-02-17T16:53:41.590

@ntorkrnl nice one +1'd ; btw got the compiler to stackoverflow already (compiler runs inside the VM, too fyi) – masterX244 – 2014-02-17T18:41:18.593

For those of us who don't know much about Java internals, can you explain why this terminates? – Justin Morgan – 2014-02-26T16:12:54.887

@JustinMorgan It terminates because it's not an infinite loop. If you think of the program as a 1024-bit binary counter where a stack frame in the try block is a 0 and finally is a 1, then the program steps through all possible states of the counter, throwing a stack overflow error every time. A similar program should work in C# as well. – ntoskrnl – 2014-02-26T16:28:01.303

I checked c# version, It did take less than second to blow UP (stackoverflow). class Program { static void Main(string[] args) { recurse(); }

    private static void recurse()
    {
        try
        {
            recurse();
        }
        finally
        {
            recurse();
        }
    }
}
 – codeSetter  – 2014-03-02T13:15:36.947

@Dipak Seems that I was wrong about C#. According to the documentation, you cannot catch a stack overflow in modern versions of .NET.

– ntoskrnl – 2014-03-02T17:14:35.847

The Ruby equivalent is ruby -e 'def r; r; ensure; r; end; r. It would not stop until I sent SIGKILL. – kernigh – 2014-05-13T01:37:50.003

I may have misunderstood; by 'terminates,' do you mean it eventually errors out? That would make sense. – Justin Morgan – 2014-10-09T17:26:13.593

@JustinMorgan Yes, in theory it will eventually error out with a stack overflow. In practice, that won't happen in the lifetime of the universe. – ntoskrnl – 2014-10-09T19:04:30.487

30

C#

First post, so please go easy on me.

class Program
{
    static void Main()
    {
        new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Invoke(null, null);
    }
}

This simply creates a stack trace, grabs the top frame (which will be our last call to Main()), gets the method, and invokes it.

BenM

Posted 2014-02-17T08:57:34.803

Reputation: 1 409

You should comment that code with " what could possibly go wrong ? " :P – Spaceman – 2015-10-21T06:42:42.597

nice way of selfinvoke which isnt that obvious without explain; +1'd – masterX244 – 2014-02-19T19:00:57.280

26

Java

  • In Java 5, printStackTrace() enters an infinite loop.
  • In Java 6, printStackTrace() throws StackOverflowError.
  • In Java 7 and 8, it was fixed.

The crazy thing is that in Java 5 and 6, it does not comes from user code, it happens in JDK's code. No one reasonable suspects that printStackTrace() can be dangerous to execute.

public class Bad {
    public static void main(String[] args) {
        try {
            evilMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void evilMethod() throws Exception {
        Exception a = new Exception();
        Exception b = new Exception(a);
        a.initCause(b);
        throw a;
    }
}

Victor Stafusa

Posted 2014-02-17T08:57:34.803

Reputation: 8 612

7yeah; stackoverflows out of nothing are the best friend for codetrolling and a serious headache on hunting em – masterX244 – 2014-02-17T10:31:14.893

2If anyone wonders, equivalent code in C# causes an infinite loop. But InnerException property is read-only and is set in constructor, so reflection is necessary to cause this. – Athari – 2014-02-22T11:38:37.713

17

JavaScript: Non-recursive, iterative function mutation

var f = function() {
    console.log(arguments.length);
};

while (true) {
    f = f.bind(null, 1);
    f();
}

There's no recursion here at all. f will be repeatedly curried with more and more arguments until it can overflow the stack in a single function call. The console.log part is optional in case you want to see how many arguments it takes to do it. It also ensures that clever JS engines won't optimize this away.

Code-golf version in CoffeeScript, 28 chars:

f=->
do f=f.bind f,1 while 1

Justin Morgan

Posted 2014-02-17T08:57:34.803

Reputation: 556

14

C# with an epic fail

using System.Xml.Serialization;

[XmlRoot]
public class P
{
    public P X { get { return new P(); } set { } }
    static void Main()
    {
        new XmlSerializer(typeof(P)).Serialize(System.Console.Out, new P());
    }
}

The way it fails is epic, it blew my mind completely:

enter image description here

It is just one frame of a seemingly infinite tripping series of strange images.

This has got to be the weirdest thing ever. Can anybody explain? Apparently, the ever increasing amount of spaces used for indentation cause those white blocks to appear. It happens on a Win7 Enterprise x64 with .NET 4.5.

I haven't actually seen the end of it yet. If you replace System.Console.Out with System.IO.Stream.Null, it dies pretty fast.

The explanation is pretty simple. I make a class which has a single property, and it always returns a new instance of its containing type. So it's an infinitely deep object hierarchy. Now we need something which tries to read through that. That's where I use the XmlSerializer, which does just that. And apparently, it uses recursion.

fejesjoco

Posted 2014-02-17T08:57:34.803

Reputation: 5 174

yeah; serializing ftw :P; but more funny is it when ythe quirk is completely outside of your code like how snakeyaml gets the attributes and one class returns itself in a way that endlesly recurses – masterX244 – 2014-02-20T17:39:13.847

1Well, the overflow does happen outside of my code, but the real reason I posted this is because of the unexpected side effect in the console :-) – fejesjoco – 2014-02-20T17:50:54.743

I think the white bits must be to either to do with .Net 4.5 or how your environment is set up, because using .Net 4 (even when run through cmd) I only get spaces, no white blocks. My guess is that either the Win7 Enterprise version of cmd or the .Net 4.5 console emulator treat a certain character combination as 'change the console colour background'. – Pharap – 2014-02-23T03:13:02.180

I can't reproduce it with .NET 4.5 on Win7 x64 Professional with Aero turned on – Ray – 2014-03-18T13:08:12.017

Can't reproduce, either. .NET 4.5, Windows 8.1 Pro. – bwDraco – 2014-10-02T03:35:49.053

13

bash

_(){ _;};_

While many might recognize that the recursion is obvious, but it seems pretty. No?

Upon execution, you are guaranteed to see:

Segmentation fault (core dumped)

devnull

Posted 2014-02-17T08:57:34.803

Reputation: 1 591

5this one is prettier and worse: _(){_|_;};_ – RSFalcon7 – 2014-02-17T15:03:24.183

1@RSFalcon7 Forkbomb alert! (Also, doesn't it need a space after the { to be syntactically correct?) – Blacklight Shining – 2014-02-17T15:08:34.390

Yes! and yes! Forkbomb are beautiful :) Sorry about the space – RSFalcon7 – 2014-02-17T15:24:42.373

3Try this as well :(){:|:;}: – Tarek Eldeeb – 2014-02-17T16:17:50.297

Just a small note. On zsh for example the space is not required. – hashier – 2014-02-18T11:35:58.447

14Looks like a creepy, mutant emoticon. – Tim Seguine – 2014-02-18T21:00:02.950

8Bash emoticons: eater of faces, killer of stacks. – NobleUplift – 2014-02-20T19:27:12.057

12

Haskell

(sad but true until at least ghc-7.6, though with O1 or more it'll optimise the problem away)

main = print $ sum [1 .. 100000000]

ceased to turn counterclockwis

Posted 2014-02-17T08:57:34.803

Reputation: 5 200

shouldn't it do a tail call optimization automatically (in sum)? – blabla999 – 2014-02-17T11:55:30.310

2@blabla999: tail-calls aren't that relevant in Haskell, it's mostly thunk buildup due to covert lazyness that's causing such problems. In this case, the issue is that sum is implemented in terms of foldl, which does use tail calls, but because it doesn't evaluate the accumulator strictly merely produces a pile of thunks as large as the original list. The problem disappears when switching to foldl' (+), that evaluates strictly and thus returns a WHN in its tail call. Or, as I said, if you switch on GHC's optimisations! – ceased to turn counterclockwis – 2014-02-17T13:13:54.250

aah - interesting, so if no one would wait for the thunk (i.e. leaving out the print), the garbage collector would collect them away (from front to back)? – blabla999 – 2014-02-17T13:23:41.253

@blabla999: well, leaving out the print would simply mean foldl never even starts to do anything: there would be just a single thunk representing the entire sum (_) expression, and that would then be GC'ed in one go. But, yeah, the GC can in more interesting cases collect thunks as-you-go, that's where lazyness becomes really interesting (e.g. allowing you to process infinite lists). – ceased to turn counterclockwis – 2014-02-17T13:38:28.783

1BTW, none of this is really specified by the Haskell standard: it's merely required that evaluation is non-strict, i.e. a nonterminating computation won't block forever if the result is not fully required. How long it really blocks is up to the implementation, in standard lazy GHC it doesn't block at all until you request the result. – ceased to turn counterclockwis – 2014-02-17T13:44:00.507

2haskell is cool. – blabla999 – 2014-02-17T14:15:46.023

12

Smalltalk

This creates a new method on the fly, which
  creates a new method on the fly, which
    creates a new method on the fly, which
      ...
    ...
  ..
and then transfers to it.

An extra little spice comes from stressing stack memory AND heap memory at the same time, by creating both a longer and longer method name, and a huge number as receiver, as we fall down the hole... (but the recursion hits us first).

compile in Integer:

downTheRabbitHole
    |name deeperName nextLevel|

    nextLevel := self * 2.
    name := thisContext selector.
    deeperName := (name , '_') asSymbol.
    Class withoutUpdatingChangesDo:[
        nextLevel class 
            compile:deeperName , (thisContext method source copyFrom:name size+1).
    ].
    Transcript show:self; showCR:' - and down the rabbit hole...'.
    "/ self halt. "/ enable for debugging
    nextLevel perform:deeperName.

then jump, by evaluating "2 downTheRabbitHole"...
...after a while, you'll end up in a debugger, showing a RecursionException.

Then you have to cleanup all the mess (both SmallInteger and LargeInteger now have a lot of wonderland code):

{SmallInteger . LargeInteger } do:[:eachInfectedClass |
    (eachInfectedClass methodDictionary keys 
        select:[:nm| nm startsWith:'downTheRabbitHole_'])
            do:[:each| eachInfectedClass removeSelector:each]

or else spend some time in the browser, removing alice's wonderland.

Here is some from the head of the trace:

2 - and down the rabbit hole...
4 - and down the rabbit hole...
8 - and down the rabbit hole...
16 - and down the rabbit hole...
[...]
576460752303423488 - and down the rabbit hole...
1152921504606846976 - and down the rabbit hole...
2305843009213693952 - and down the rabbit hole...
[...]
1267650600228229401496703205376 - and down the rabbit hole...
2535301200456458802993406410752 - and down the rabbit hole...
5070602400912917605986812821504 - and down the rabbit hole...
[...]
162259276829213363391578010288128 - and down the rabbit hole...
324518553658426726783156020576256 - and down the rabbit hole...
[...]
and so on...

PS: the "withoutUpdatingChangesFile:" was added to avoid having to cleanup Smalltalk's persistent change-log file afterwards.

PPS: thanks for the challenge: thinking about something new and innovative was fun!

PPPS: I like to note that some Smalltalk dialects/versions copy overflowing stack frames to the heap - so these may run into an out-of-memory situation instead.

blabla999

Posted 2014-02-17T08:57:34.803

Reputation: 1 869

2LOL +1 for that black magic in its pure form – masterX244 – 2014-02-17T11:42:29.247

If I find some time, I may "improve" by using an anonymous method of an anonymous class, to make the darkest rabbit hole ever... – blabla999 – 2014-02-18T10:59:47.143

12

C#

Really big struct, no recursion, pure C#, not unsafe code.

public struct Wyern
{
    double a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
}
public struct Godzilla
{
    Wyern a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
}
public struct Cyclops
{
    Godzilla a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
}
public struct Titan
{
    Cyclops a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
}
class Program
{
    static void Main(string[] args)
    {
        // An unhandled exception of type 'System.StackOverflowException' occurred in ConsoleApplication1.exe
        var A=new Titan();
        // 26×26×26×26×8 = 3655808 bytes            
        Console.WriteLine("Size={0}", Marshal.SizeOf(A));
    }
}

as a kicker it crashes the debug windows stating that {Cannot evaluate expression because the current thread is in a stack overflow state.}


And the generic version (thanks for the suggestion NPSF3000)

public struct Wyern<T>
    where T: struct
{
    T a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;        
}


class Program
{
    static void Main(string[] args)
    {
        // An unhandled exception of type 'System.StackOverflowException' occurred in ConsoleApplication1.exe
        var A=new Wyern<Wyern<Wyern<Wyern<int>>>>();
    }
}

ja72

Posted 2014-02-17T08:57:34.803

Reputation: 437

Needs more Generic code methinks :P – NPSF3000 – 2014-02-20T13:02:02.467

The it would look like recursion, but it is possible with nested type arguments. – ja72 – 2014-02-20T14:05:41.747

1Didn't see your C# struct answer before I posted mine. I still have a little different approach, so maybe we let them coexist. – Thomas Weller – 2014-02-20T15:21:27.027

11

Starting reply using SnakeYAML

class A
{

    public static void main(String[] a)
    {
         new org.yaml.snakeyaml.Yaml().dump(new java.awt.Point());
    }
}

Edit: ungolfed it

Its up to the reader to find out how that works :P (tip: stackoverflow.com)

By the way: the recursion is dynamically made by SnakeYAML (you will notice if you know how it detects the fields it serializes and look then in Point's sourcecode)

Edit: telling how that one works:

SnakeYAML looks for a pair of getXXX and setXXX mthod with same name for XXX and return type of the getter is same as parameter of setter; and surprisingly the Point class has a Point getLocation() and void setLocation(Point P) which returns itself; SnakeYAML doesn't notice it and recurses on that quirk and StackOverflows. Discovered that one when working with them inside a HashMap and asking on stackoverflow.com on it.

masterX244

Posted 2014-02-17T08:57:34.803

Reputation: 3 942

11

C#

Faulty implementation of overriden == operator:

public class MyClass
{
    public int A { get; set; }

    public static bool operator ==(MyClass obj1, MyClass obj2)
    {
        if (obj1 == null)
        {
            return obj2 == null;
        }
        else
        {
            return obj1.Equals(obj2);
        }
    }

    public static bool operator !=(MyClass obj1, MyClass obj2)
    {
        return !(obj1 == obj2);
    }

    public override bool Equals(object obj)
    {
        MyClass other = obj as MyClass;
        if (other == null)
        {
            return false;
        }
        else
        {
            return A == other.A;
        }
    }
}

One might say it's obvious that operator== calls itself by using the == operator, but you usually do not think that way about ==, so it's easy to fall into that trap.

Sebastian Negraszus

Posted 2014-02-17T08:57:34.803

Reputation: 1 471

10

C#

wrongly implemented property getter

class C
{
   public int P { get { return P; } }
}

static void Main()
{
   int p = new C().P;
}

Alberto

Posted 2014-02-17T08:57:34.803

Reputation: 404

how does the black magic work? – masterX244 – 2014-02-17T13:55:39.003

The property getter will be compiled in a method (get_P), so essentially it is calling the method get_P recursively. – Alberto – 2014-02-17T13:58:42.433

14IMHO. This is a classic example for an obvious recursion... (and so not valid) – Ole Albers – 2014-02-17T14:57:20.213

2Well, it's only obvious once you've done it once and figured out that C# getters don't work the way you may have thought they did. After all, this code is a member variable declaration, so why shouldn't it create an actual member variable? – meustrus – 2014-02-17T19:30:58.053

2This is no more than a convoluted way of doing static void Main() { Main(); } – Jodrell – 2014-02-18T09:42:46.217

5@Jodrell You wouldn't write recursive Main() accidentally. But it's quite simple to write a recursive property accidentally and then be confused by the stack overflow. – svick – 2014-02-18T17:01:34.373

1This would be useful for someone picking up C#. – 2rs2ts – 2014-02-20T14:10:27.200

I have seen so many questions on Stackoverflow about this situation, examples here, here and lots of others(search on google: stackoverflow exception on setting property in C# site:stackoverflow.com), it may not be that weird but it is very common and can be really confusing for new developer

– Habib – 2014-02-20T14:22:52.290

That moment when I did this while I was re-learning C# (learned it in undergraduate, was too much of a Java programmer by graduate school). – NobleUplift – 2014-02-20T19:29:47.203

7

Java

import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class HiddenStackOverflow extends JPanel implements MouseMotionListener {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("Animate Circle around Mouse Pointer");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new HiddenStackOverflow());
                frame.setVisible(true);
            }

        });
    }
    int x, y;

    public HiddenStackOverflow() {
        this.addMouseMotionListener(this);
        x = y = 0;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paint(g);
        g.fillOval(x - 50, y - 50, 100, 100);
    }

    @Override
    public void mouseDragged(MouseEvent me) {
        mouseMoved(me);
    }

    @Override
    public void mouseMoved(MouseEvent me) {
        x = me.getX();
        y = me.getY();
        repaint();
    }
}

This is a mistake that I actually made. Do not get paint and paintComponent mixed up.

If the super.paint(g) in method paintComponent were correctly written as super.paintComponent(g), this program will continuously draw a black circle around the mouse pointer.


In response to some comments claiming this is obvious recursion, this is why I consider this not obvious:

  • I occasionally make this mistake (made it often when I first started coding Swing).
  • Rely's on "hidden code" (hidden in Swing and AWT) to create the recursion.
  • calls the superclass method, not the "this" class.

Justin

Posted 2014-02-17T08:57:34.803

Reputation: 19 757

2Isn't that an obvious recursion though, if my memory of how AWT works is not altered? – Pierre Arlaud – 2014-02-17T09:47:01.347

1@ArlaudPierre Not AWT, Swing. You might call it obvious, but I have mistyped that way many times. It is really easy to do so. I would not call it that obvious; for one, it calls the superclass's method, not the class's itself. – Justin – 2014-02-17T09:48:47.847

and its relying on the java awt behavior :P (sometimes APIS have pretty odd behavior; see my YAML one) – masterX244 – 2014-02-17T09:50:11.470

1@masterX244 why is everyone calling Swing AWT! They are very different. Swing comes in a completely different project (javax, not java). Sure, Swing does rely on AWT, but it is quite different in what it can do. – Justin – 2014-02-17T09:53:39.323

@Quincunx paint(java.awt.Graphics) is in AWT, while paintComponent is in swing. By polymorphism, my calling this the work of AWT is true considering Swings JComponent extend AWT Component. I don't know why we're even argueing about this. Anyway, the point is this answer is invalid according to the rules. – Pierre Arlaud – 2014-02-17T09:59:27.200

@ArlaudPierre It is not invalid. This is not an obvious recursion. Yes I know Swing is an extension on AWT and I know about all those things that you mentioned. I was just surprised to see that this code is being called AWT when I was coding in Swing. Sorry for seeming argumentative. – Justin – 2014-02-17T10:05:08.000

@ArlaudPierre same as Quincunx It isnt that oobvious cause you need to know how the backstage logic of Swing is and if not you may headscratch... – masterX244 – 2014-02-17T10:15:46.557

2@masterX244 But it's basically like your second example, except the methodA is "hidden" and you're not the one to have programmed it. – Pierre Arlaud – 2014-02-17T10:16:44.810

@ArlaudPierre due to it being hidden outside of your code it isnt obvious anymore. – masterX244 – 2014-02-17T10:17:48.923

Fair enough, ununvoted (is that a word?) :) – Pierre Arlaud – 2014-02-17T10:20:13.373

2@ArlaudPierre What you are looking for is un-downvoted. :-) – Justin – 2014-02-17T10:23:48.310

6

JavaScript - not a single expression

{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{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}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}

Here is why it works

Benjamin Gruenbaum

Posted 2014-02-17T08:57:34.803

Reputation: 219

Editing it causes my browser to slow down absurdly - so for people not wanting to follow the link - this causes a stack overflow in the JS parser in all modern browsers since they are written in recursive descent. – Benjamin Gruenbaum – 2014-02-26T11:47:08.813

The Firefox console returns: InternalError: too much recursion – bwDraco – 2014-10-02T03:37:51.207

5

Java

They always tell you not to reinvent the wheel, so I used collections from java.util.

Set<Object> s = new HashSet<>();
s.add(s);
s.add(s);

And here's a simple list implementation extending the built-in java.util.AbstractList:

public class MyList<E> extends AbstractList<E> {

    private Object[] contents;

    public static void main(String[] args) {
        MyList<String> list = new MyList<>( "Roses", "are", "red" );
        System.out.println( list );
    }

    public MyList( E... fill ){
        contents = new Object[fill.length];
        for( int i=0; i<fill.length; i++ )
            contents[i] = fill[i];
    }

    @Override
    public E get(int i) {
        return (E)contents[i];
    }

    @Override
    public int size() {
        int i = 0;
        for( E e : this ) ++i;
        return i;
    }
}

trutheality

Posted 2014-02-17T08:57:34.803

Reputation: 221

nice way :) funnily how java fails on hashcoding on a hashset with the set added ti itself 2x... – masterX244 – 2014-02-18T08:26:27.507

5

C#

Value types are created on the stack and stacks are usually 1 MB in size, so a simple struct will do...

using System.Runtime.InteropServices;
namespace N
{
    [StructLayout(LayoutKind.Explicit)]
    struct A
    {
        [FieldOffset(0xFFFFC)]
        public int a;
    }

    class P
    {
        static void Main()
        {
             A a= new A();
             Console.WriteLine(a.a);
        }
    }
}

I think it's even better if it comes a bit more subtle:

using System.Runtime.InteropServices;
using Debug=System.Console;
namespace N
{
    [StructLayout(LayoutKind.Explicit)]
    struct Console
    {
        [FieldOffset(0xFFFFC)] public int WriteLine;
    }

    class P
    {
        static void Main()
        {
            var console= new Console();
            Debug.WriteLine(console.WriteLine);
        }
    }
}

Thomas Weller

Posted 2014-02-17T08:57:34.803

Reputation: 1 925

+1 I like the idea of using an [FieldOffset] attribute. – ja72 – 2014-02-20T15:38:13.017

4

C + GCC inline assembly

Same idea as Michael Ehrenreich's answer.

int f() {
        printf("Hello, world\n");
        asm(".section return");
}
asm(".previous");

int main() {
        f();
        return 0;
}

The return from f is moved to another section, and not executed.

ugoren

Posted 2014-02-17T08:57:34.803

Reputation: 16 527

4

C, POSIX

#include <signal.h>
#include <stdlib.h>

void
foo(int sig)
{
        *(int *)sig = sig;
}

int
main(int argc, char **argv)
{
        struct sigaction sa;

        sa.sa_handler = foo;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = SA_NODEFER;
        sigaction(SIGSEGV, &sa, NULL);
        foo(42);

        return 0;
}

Should work on all POSIX systems. Only tested on MacOS and Linux. The final crash is because of a stack overflow even though there isn't really a way for the system to tell you it was one. Throw the core dump into a debugger if you don't believe that.

Art

Posted 2014-02-17T08:57:34.803

Reputation: 545

4

Android / XML drawable

Save as drawable/ololo.xml and open in IntelliJ IDEA editor. It will display java.lang.StackOverflowError.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ololo"/>
</selector>

Display Name

Posted 2014-02-17T08:57:34.803

Reputation: 654

4

Java

Picked up from here, it causes an StackOverflowError in the compiler:

class T { }
class N<Z> { }
class C<X> extends N<N<? super C<C<X>>>> {
  N<? super C<T>> cast(C<T> c) { return c; }
}

devnull

Posted 2014-02-17T08:57:34.803

Reputation: 1 591

Welcome in the club :) second one to stackoverflow javac :) i got it to stakoverflow by spamming it with variables; using the way to compile code you ahve as string inside another program to generate the millions of variables needed to get javac to reject – masterX244 – 2014-02-18T13:29:04.033

See this paper: http://research.microsoft.com/en-us/um/people/akenn/generics/FOOL2007.pdf

– Eric Lippert – 2014-02-18T18:11:23.483

4

EcmaScript 6 (only 19 bytes!):

atob(...Array(9e5))

It uses absolutely no recursion, and it's a fully-valid program!

Toothbrush

Posted 2014-02-17T08:57:34.803

Reputation: 3 197

4

Python

This is one I've seen in practice, by accident:

class test(object):
    mainvalue=1
    def __getattribute__(self,attrname):
        return self.mainvalue


print test().blah

The catch is that, if you define __getattr__ instead of __getattribute__, it works exactly as expected (it prints 1)

AMADANON Inc.

Posted 2014-02-17T08:57:34.803

Reputation: 181

4

C#

var x = "Joel Spolsky";
var y = "Jeff Atwood";

var stackOverflow = x + y;

(Actual program output may vary)

Paddy

Posted 2014-02-17T08:57:34.803

Reputation: 138

how does it work? – masterX244 – 2014-02-19T19:00:13.467

@masterX244: StackOverflow.com is created by Joel Spolsky and Jeff Atwood. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-02-20T12:54:43.770

1ahhh :) nifty way to reinterpret the question :P +1 for thinking outside the box – masterX244 – 2014-02-20T13:01:23.897

4

C (via ATL)

#include <AtlBase.h>
int main() {
     for(;;) 
         printf("%s\n", W2CA("STACKOVERFLOW"));
     return 0;
}

Even for people who do code C, this looks like it simply loops forever printing "STACKOVERFLOW" to the screen. Turns out the W2CA is a macro that behind-the-scenes allocates stack memory which isn't released until the function returns. If you use it in a loop, a stack-overflow is a common (usually highly unexpected) result. Microsoft eventually deprecated this macro for this problem. This is effectively the same as Ruslan's answer, except less obvious what's going on.

Mooing Duck

Posted 2014-02-17T08:57:34.803

Reputation: 143

What exactly does this do (for us who don't code in C)? – Justin – 2014-02-20T01:03:33.727

1Even for people who do code C, this looks like it simply loops forever printing "STACKOVERFLOW" to the screen. Turns out the W2CA is a macro that behind-the-scenes allocates stack memory which isn't released until the function returns. If you use it in a loop, a stack-overflow is a common (usually highly unexpected) result. Microsoft eventually deprecated this macro for this problem. This is effectively the same as Ruslan's answer, except less obvious what's going on. – Mooing Duck – 2014-02-20T01:14:40.497

4

dc

With dc(1) in OpenBSD 5.5, adding a comment or whitespace to a program may overflow the stack.

Both of these programs have obvious recursion. They are infinite loops, and all loops in dc are tail-recursive. The surprise is that the first program never overflows:

[lwx]dswx

The second program does overflow:

[
 lw x   # loop forever
] d sw x

The only difference is that the second program has extra comments and whitespace. OpenBSD dc optimizes tail recursion only when the tail call, such as x, is immediately before the end bracket ]. So, the first program loops forever. In the second program, dc wants to return and run the commands between the x and the ], so dc overflows the call stack.

dc: recursion too deep: Cannot allocate memory

To prevent overflow, I must play code golf and delete all comments and whitespace between the x and the ].

kernigh

Posted 2014-02-17T08:57:34.803

Reputation: 2 615

3

Batch

@call me Al
    ~ Paul Simon

Save to a file called me.bat. Or add the label :me at the start of this batch file and change @call me Al to @call :me Al.

unclemeat

Posted 2014-02-17T08:57:34.803

Reputation: 2 302

3

Batch

call _

Save it to a file _.bat and execute it!

The code, per se, doesn't make the recursion obvious. Upon executing, you'd see:

....
....
******  B A T C H   R E C U R S I O N  exceeds STACK limits ******
Recursion Count=1240, Stack Usage=90 percent
******       B A T C H   PROCESSING IS   A B O R T E D      ******

devnull

Posted 2014-02-17T08:57:34.803

Reputation: 1 591

This is essentially the same as my answer. But I feel like there must be a more clever way to produce this error with Batch.

– unclemeat – 2014-02-17T21:49:31.883

1It's funny how stupid the error message looks, like a 90's computer movie error with big letters and spaces and stars. – Ray – 2014-03-18T13:11:12.233

3

Python

forking isn't recursion, right?

import os
while 1: os.fork()

devnull

Posted 2014-02-17T08:57:34.803

Reputation: 1 591

the fork bong according to python :) – Kiwy – 2014-02-17T13:49:16.980

11fork bong? – We Are All Monica – 2014-02-17T19:36:43.380

3A fork bomb perhaps?? – Carl Smith – 2014-02-17T21:33:48.093

these days, you have to be careful with such words (bb is listening) [sorry, couldn't resist commenting) – blabla999 – 2014-02-19T10:56:34.710

3

bash

#!/bin/bash

touch $'\x3b'
bash -c "echo $(ls ./*)"

Usage

Save as ls (any other filename works as well), make executable and call as ./ls.

What it does

  • touch $'\x3b' creates a file called ;.

  • $(ls ./*) gets replaced by contents of the current directory.

    Example:

    ./; ./ls
    
  • bash -c "echo ./; ./ls" executes the following in a subshell:

    echo ./
    ./ls
    

Dennis

Posted 2014-02-17T08:57:34.803

Reputation: 196 637

3

Common Lisp (GNU CLISP)

[1]> (lambda () (funcall *))
#<FUNCTION :LAMBDA NIL (FUNCALL *)>
[2]> (funcall *)

*** - Program stack overflow. RESET

Explanation (see if you can figure it out first):

The value of the variable variable * is the result of the last form evaluated at the prompt. Thus, (funcall *) says "call the last REPL result," and that happens to be (lambda () (funcall *)) which is a function that calls the last REPL result, which at that point is itself.

There are lots of variations on this theme:

[7]> (setf (symbol-function '*) (lambda () (funcall *)))
#<FUNCTION :LAMBDA NIL (FUNCALL *)>
[8]> (*)

*** - Program stack overflow. RESET

A particularly devious one would be a function that "works" (does something that's not a stack overflow) at first, and then later overflows the stack. E.g., using ** (which is the second to last REPL result):

[14]> (defun hello-world () (print 'hello-world))
HELLO-WORLD
[15]> (defun uh-oh () (funcall **))
UH-OH
[16]> (uh-oh)

HELLO-WORLD 
HELLO-WORLD
[17]> (uh-oh)

*** - Program stack overflow. RESET

Joshua Taylor

Posted 2014-02-17T08:57:34.803

Reputation: 660

3

C#, no recursion. Requires unsafe code. Attempt to allocate an array that wont fit on the stack.

class Program {
    static unsafe void Main() {
        var b = stackalloc byte[0x100000];
    }
}

MarkPflug

Posted 2014-02-17T08:57:34.803

Reputation: 131

Damn, beat me to it D: – Pharap – 2014-02-23T03:19:22.087

3

J

As J is generally a weird language, probably one of the shortest:

    $:''
| stack error
|       $: ''

An even weirder one, using every printable, non-white-space ASCII character exactly once:

!"#%&()*+,-/:;<=>?@ACDEFGHIJKLMOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~&$:0123456789 NB.'
|stack error
|   !"#%&()*+,-/:;<=>?@ACDEFGHIJKLMOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{    |}~&$:123456789

jpjacobs

Posted 2014-02-17T08:57:34.803

Reputation: 3 440

3

Lua

Using metatables frequently results in stack overflows :

a=setmetatable({},{__index=function(t,k)return t[k]end})
print(a[1]) -- index this table.

jpjacobs

Posted 2014-02-17T08:57:34.803

Reputation: 3 440

3

Ruby

evil = "eval evil"
eval evil

This will cause SystemStackError: stack level too deep

1.9.3p448 :006 >   
1.9.3p448 :007 >   evil = " eval evil"
 => " eval evil" 
1.9.3p448 :008 >   eval evil
SystemStackError: stack level too deep
    from /usr/local/rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/irb/workspace.rb:80
Maybe IRB bug!
1.9.3p448 :009 > 

Siva

Posted 2014-02-17T08:57:34.803

Reputation: 241

This recursion is obvious. – kernigh – 2014-05-13T02:02:26.037

3

C

A simple recursion. But where's the recursive call?!

#include <stdio.h>
#include <errno.h>

void f(int errno) {
        if (errno==EINVAL) puts("EINVAL");
}

int *main() {
        f(main);
        return 0;
}

Solution:

errno.h defines: #define errno *(__errno_location())
When this is expanded in the parameter list, f is defined to get a function pointer parameter, named __errno_location.
When this is expanded in the body, this function is called.
Calling f with main as a parameter leads to endless recursion.

EDIT: The previous version crashed, but not because of a stack overflow. Fixed.

ugoren

Posted 2014-02-17T08:57:34.803

Reputation: 16 527

2

Java

More API vodoo. This time, the stack trace doesn't hint where the overflow line is actually.

class SO extends JFrame
{
    public static void main(String[]a)
    {
        new SO().setVisible(true);

    }
    public SO()
    {
        setSize(100,100);
        DefaultListModel m = new DefaultListModel();
        JList l = new JList(m);
        m.addElement(m);
        add(l);
    }
}

That derp happened to me once while programming some GUI stuff and I didn't knew where it was from

masterX244

Posted 2014-02-17T08:57:34.803

Reputation: 3 942

This is unobvious recursion? Okay.... I thought that adding a list to itself is obvious, but apparently it is not. – Justin – 2014-02-17T10:20:32.420

run it and see what the trace tells you as source of overflow – masterX244 – 2014-02-17T10:22:10.940

1Lol; recursive stack trace! – Justin – 2014-02-17T10:25:36.960

However, I couldn't help but notice that it tells you that the error is from DefaultListModel. Also, I use two main steps for debugging: 1. read stack trace to see if there is a hint. 2. either apply the hint or, if there is none, debug by examining code. – Justin – 2014-02-17T10:26:07.387

but not the line where you add the model :P so if you have some more code between the setVisible it can confuzzle – masterX244 – 2014-02-17T10:26:56.877

Of course not. Most of those calls are from the DefaultListModel. My hypothesis is that the stack trace has a smaller stack than the call stack, so it automatically removes elements to keep its size within the correct amount. – Justin – 2014-02-17T10:30:32.860

1btw, you can add java syntax coloring by adding this before the code block: <!-- language: lang-java --> – Justin – 2014-02-17T10:31:07.147

2

C#

Using fixed arrays and loading struct into the stack for an operation.

public unsafe struct Godzilla
{
    public const int Size = 40900;
    fixed double data[Size];
    public Godzilla(double init)
    {
        fixed(double* ptr=data)
        {
            for(int i=0; i<Size; i++)
            {
                ptr[i]= init;
            }
        }
    }

    public void Add(Godzilla other)
    {
        fixed(double* ptr=data)
        {
            for(int i=0; i<Size; i++)
            {
                ptr[i]+=other.data[i];
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Godzilla A=new Godzilla(1.0);
        Godzilla B=new Godzilla(2.0);
        A.Add(B);
    }
}

It tries to load all the values on the stack and fails. Each struct is 8×40900 = 327,200 bytes long and when two of them get loaded into the stack it pukes.

SO

ja72

Posted 2014-02-17T08:57:34.803

Reputation: 437

2

Java and no!!! recursion anywhere :P

import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class E
{
    public static void main(String[]a)  //run with -Xmx=4G on a 64bit-OS with enough ram...
    {
        //Method m = new E().getClass().getMethod(null, parameterTypes);
        StringBuffer params = new StringBuffer();
        StringBuffer paramdef = new StringBuffer();
        int i=0;
        for (i=0; i < 1000000; i++)
        {
             params.append(i+",\n");   
             paramdef.append("int param"+i+",\n");
        }
        params.append(i);
        paramdef.append("int param"+i);
        String classheader= "class E2{public static void lickme("+paramdef.toString()+"){} static{lickme("+params.toString()+");}}";
        //dump the string to a file to see what happens internally :P
        EU c2 = new EU("stackoverflow.com", classheader);
        JavaCompiler c = ToolProvider.getSystemJavaCompiler();
        c.getTask(null, null, null, null, null,Arrays.asList(new EU[]{c2})).call();
    }
    public static void nop(int... Overflower)
    {

    }
    public static class EU extends SimpleJavaFileObject {
           final String code;
           EU(String name, String code) {
               super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),
                     Kind.SOURCE);
               this.code = code;
           }

           @Override
           public CharSequence getCharContent(boolean ignoreEncodingErrors) {
               return code;
           }
       }
}

If you wonder what happens dump the string before it get compiled; java-eval ftw :P

If you swap that line for (i=0; i < 1000000; i++) to for (i=0; i < 100 00000; i++) it stackoverflows even with -Xmx10G -Xss100M as JVM parameters and peaks at just over 9GB RAM usage.

Trick used is sme weird handling f too many Method parameters inside the Compiler

masterX244

Posted 2014-02-17T08:57:34.803

Reputation: 3 942

Oh I like this one! – Jason C – 2014-02-18T03:44:28.857

@Jason C: if you dump that source file generated and run it through javac manually it still stackoverflows :P – masterX244 – 2014-02-18T08:19:44.370

2

C# .NET mishandling unhanded exceptions:

The idea can happen in many places, such as in ASP.NET, Winforms, WPF, well everywhere where you try to handle an unhanded exception and raise another error as a result. To me, this happened in a project where the error log was written in the database, but the database connection would fail, which in turn would raise another error.

Here is a simple windows forms application to illustrate the idea:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Application.ThreadException += (sender, args) => WriteError("Unhandled Exception");
        }

        private void WriteError(string msg)
        {
            throw new Exception("Can't write!");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            throw new Exception("Overflow it!");
        }
    }
}

Candide

Posted 2014-02-17T08:57:34.803

Reputation: 121

I like how some of these answers are obvious it was discovered once as a bug. +1 Nice one. – Reactgular – 2014-02-18T23:03:50.930

2

TeX

\def~{\if~}~

At least the original TeX code crashes with a stack overflow here. Several (mostly newer) implementations take measures to avoid it, though, and bomb out with a nicer error message than "Segmentation Fault".

user16727

Posted 2014-02-17T08:57:34.803

Reputation: 51

2

This can be easily achieved using a regex pattern like this in Java. Note that the required data length to reproduce this error may change depending on your architecture.

Replacing the pattern with a better ^([a-fA-F]|\\d)++$ successfully executes the code.

Java

import java.util.regex.Pattern;

public class aRegexStackOverflow {
    public static void main(String [] whatIsThis) {
        try {
            String boom = "";
            for (int i=0; i<1292; i++)
                boom+=Integer.toHexString(0);
            System.out.println("Length: " + boom.length());
            if (Pattern.matches("^([a-fA-F]|\\d)+$", boom.trim()))
                System.out.println("This is working!");
            boom+=Integer.toHexString(0);
            System.out.println("Length: " + boom.length());
            if (Pattern.matches("^([a-fA-F]|\\d)+$", boom.trim()))
                System.out.println("This will never be printed...");
        }
        catch(StackOverflowError soe) {
            soe.printStackTrace();
        }
    }
}

Output:

Length: 1292
This is working!
Length: 1293
java.lang.StackOverflowError
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3692)
at java.util.regex.Pattern$Branch.match(Pattern.java:4502)
at ... //Goes on for a while tbh

Explanation as stated in the comments by nhahtdh (thank you!)

Oracle's implementation of Pattern class uses recursion for matching greedy/lazy repetition of a non-trivial pattern. This explains the behavior. Some other JVM which reimplements the Pattern class (such as GNU classpath) and use data structure to simulate the recursion will not have this behavior.


Inspiration: Oracle Bug Database (even if this is not an actual bug)

Vereos

Posted 2014-02-17T08:57:34.803

Reputation: 4 079

1I was going to post something similar. Oracle's implementation of Pattern class uses recursion for matching greedy/lazy repetition of a non-trivial pattern. This explains the behavior. Some other JVM which reimplements the Pattern class (such as GNU classpath) and use data structure to simulate the recursion will not have this behavior. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-02-19T13:43:27.393

@nhahtdh Brilliant! I didn't know that! – Vereos – 2014-02-19T14:12:02.260

2

Java:

The idea is to fill the stack with one huge stack frame, containning multiple local variables, rather then with multiple stack frames:

public class LocalVarOverFlow {

    public static void main(String args[]) {
        long
                l1 = 0, l2 = 0, l3 = 0, l4 = 0, l5 = 0,
                l6 = 0, l7 = 0, l8 = 0, l9 = 0, l10 = 0,
                l11 = 0, l12 = 0, l13 = 0, l14 = 0, l15 = 0,
                l16 = 0, l17 = 0, l18 = 0, l19 = 0, l20 = 0,

                ... ;
    }
}

Elist

Posted 2014-02-17T08:57:34.803

Reputation: 121

yeah thats what generated code helps :P; see my examples on code that generates the overflow code :P and as it is generated it is postable complete :P and if done far enough it may even stackoverflow the compiler :P) – masterX244 – 2014-02-19T18:58:03.583

2

Java (Regex Compile)

The other Java regex answer (+1'd) SOEs on matching. Here's one that SOEs on compiling:

public class PatternSOE {
    public static void main(String[] args) {
        String rep = new String(new char[9999]);
        Pattern.compile(rep.replace("\0", "(") + "a" + rep.replace("\0", ")"));
    }
}

Basically builds and attempts to compile up a huge regex in the form:

 "((( ... (a) ... )))"

The regex parser recurses on each sub-group.

ɲeuroburɳ

Posted 2014-02-17T08:57:34.803

Reputation: 401

+1 for something new. But I really doubt anyone would run into this in actual usage. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-02-20T13:00:00.820

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ With the amount of reflection addicts around, I wouldn't be surprised if there are people who do run into this kind of situation. – Pharap – 2014-02-23T01:41:55.103

2

Java

Recursive reflection:

import java.lang.reflect.Method;

public class StackOverflow {
    public static void main(String[] _) throws Exception {
        Method m = Method.class.getMethod("invoke", Object.class, Object[].class);
        Object[] args = { m, null };
        args[1] = args;
        m.invoke(m, args);
    }
}

I'd like to think that this code doesn't obviously cause a stack overflow, and I'd hope the 1.8MiB of stacktrace it generates counts as 'clearly visible'.

Idea shamelessly lifted from http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4185411.

Luke Woodward

Posted 2014-02-17T08:57:34.803

Reputation: 121

2

C Buffer Overflow

#include <stdio.h>
#include <math.h>

int main()
{
   char buff[20];
   sprintf(buff, "Value of Pi = %f", M_PI);
   return(0);
}

kaar3k

Posted 2014-02-17T08:57:34.803

Reputation: 121

<string.h> isn't used, so you may want to remove it. Also, while being syntactically valid, why did you put the bracket around the 0 in the return statement? – user12205 – 2014-02-20T14:12:00.697

Good Point @ace i have removed <string.h> .Was trying to get buf overflow using string functions.Finally found this to be more simple.Brackets are habit :) – kaar3k – 2014-02-20T14:41:51.180

2

PHP

<?php
header("Location: {$_SERVER['PHP_SELF']}");

Navigating to this page produces this result:

enter image description here

Salman A

Posted 2014-02-17T08:57:34.803

Reputation: 151

2

Apache mod_rewrite done wrong

RewriteEngine On
RewriteRule ^(.+)$ /$1.php [L]

The rule, which is supposed to map URLs such as /about-us to /about-us.php, ends up producing this error in Apache logs (the L flag does not help):

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

Salman A

Posted 2014-02-17T08:57:34.803

Reputation: 151

2

Although it's not a real stack overflow but effects are pretty much the same.

int main()
{
    asm("movl $0, %esp");
}

C++ (since there is no return from main) and i386-like cpus.

ESP is the stack pointer in i386 processor, by doing that, we're pointing the stack out of the memory reserved for it, something similar happens when recursion is involved - just without actually writing to it.

Notice that SIGSEGV is generated not when ESP is changed but when the the program uses the stack, so if we modify the code like this

#include <iostream>

void foo()
{
    std::cout << "hello";
}

int main()
{
    asm("movl $0, %esp");
    foo();
}

we will get the crash at:

Program received signal SIGSEGV, Segmentation fault.
main () at stack.cpp:11
11        foo();

The interesting thing about SO is that you cannot catch SIGSEGV signal by using signal() function since there no stack to call it, but you can provide alternate stack (eg heap allocated) to the sigaction function.

Piotrek

Posted 2014-02-17T08:57:34.803

Reputation: 21

2

Haskell

A joke I thought of a couple of years back:

import Control.Monad.Fix

main = print(fix error)

gives

"*** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: ... etc.

I'm not getting a stack overflow error, but maybe that is because the Glasgow Haskell Compiler uses lazy evaluation.

The function fix :: (a -> a) -> a gives the first fix point of the function error - fix applies a function to itself. In that sense it is plain and simple recursion. The function error :: [Char] -> a requires a string argument and returns something of any type. That is why it can serve as the argument to another error function.

Angelorf

Posted 2014-02-17T08:57:34.803

Reputation: 121

2

Python and the Y combinator

before someone else does it:

(lambda f: (lambda x: x(x))(lambda y: f(lambda : y(y)())))(lambda f: f)()

Please, if you don't know much about lambda calculus, don't downvote this solution because you believe that the recursive call is obvious; it isn't obvious at all. More precisely, lambda x: x(x) or lambda : y(y) or lambda f: f ARE NOT recursive calls but mere functions applying to functions.

Thomas Baruchel

Posted 2014-02-17T08:57:34.803

Reputation: 1 590

In Ruby, ruby -e '->(f){->(x){x[x]}[->(y){f[->{y[y][]}]}]}[->(f){f}][]' – kernigh – 2014-05-13T03:39:27.583

2

C with GCC extensions

int main() {
  goto *(void*)main;
  return 0;
}

This will compile without errors and without using any compiler flags when using GCC. GCC allows "computed gotos", where you can jump directly to a pointer. It doesn't look like the goto would cause a stack overflow, but GCC puts a preamble in the main() function that pushes one register to the stack, as can be seen in the produced assembler:

main:
  pushq %rbp
  movq  %rsp, %rbp
  movl  $main, %eax
  jmp   *%rax

G. Sliepen

Posted 2014-02-17T08:57:34.803

Reputation: 580

1

AppleSoft BASIC

0 GOSUB 0

Not so weird but worth mentioning...

Paolo

Posted 2014-02-17T08:57:34.803

Reputation: 111

1This looks like a direct recursion. – Victor Stafusa – 2014-02-18T00:42:53.297

A agree, very obvious recursion. Don't meet objective nr. 2 of the OP. – Paolo – 2014-02-18T12:53:29.793

The only way to blow the stack in old BASIC is GOSUB or FOR without next. – Joshua – 2014-06-23T15:21:58.830

1

Java again :) Serializing FTW :P

public class C {
    public static class Ci implements Serializable {
        public Object o;
    }

    public static void main(String[] a) throws IOException, InterruptedException {
        List l = new ArrayList<>();
        ObjectOutputStream o = new ObjectOutputStream(new OutputStream(){
            public void write(int b) {/*DEVNULL*/}
        });

        Ci c = new Ci();
        Ci c2 = null;
        int i = 0;
        for (;;) {
            i++;
            if (i % 100000 == 0) {
                System.out.println("Serializing...");
                o.writeObject(c);
                o = new ObjectOutputStream(new OutputStream(){
                    public void write(int b) {/*DEVNULL*/}
                });
                Thread.sleep(1000);
            }

            if (false) 
                break;

            c2 = c;
            c = new Ci();
            c.o = c2;
        }
    }
}

Googling a bit around should tell how this one works :P

The modulo operator is to reduce workload and speed the thing up.

masterX244

Posted 2014-02-17T08:57:34.803

Reputation: 3 942

1

Go

I challenge anybody to see the bug, who doesn't already know where it is. I added a few (truthful) comments to explain the code to non-Goers.

Try to find it yourself, if you're so inclined, before reading the comment section below (where somebody will surely spoil it.)

Here is a link to the playground: http://play.golang.org/p/UwunxiXKP7

package main

import "fmt"

// Aim: to define an integer type that by default is printed in hex notation (0xab..)
type hexInt int

// Implementation of the Stringer interface, used by Println for conversion to string.
func (h hexInt) String() string {
    // "%#x" is the alternate form of "%x", which uses lowercase a-f and adds 0x in front.
    return fmt.Sprintf("%#x", h)
}

func main() {
    // Create a variable of type hexInt with the value 42 and print it.
    var h hexInt = 42
    fmt.Println(h)
}

Tobia

Posted 2014-02-17T08:57:34.803

Reputation: 5 455

print feedback loop? – masterX244 – 2014-02-17T20:06:32.983

"print feedback"? no, not quite. – Tobia – 2014-02-17T20:07:29.970

meant that it gets stuck in the stringification process :P – masterX244 – 2014-02-17T20:19:48.243

well, it kind of does ;) – Tobia – 2014-02-17T20:24:35.400

Clever. You can add a link to go playground so that people can test it: http://play.golang.org/p/UwunxiXKP7

– Art – 2014-02-18T08:00:25.103

1

Python:

Using anonymous recursion. I'm not sure if this is too straight-forward or not, but there are no declared functions, so it seems potentially interesting.

(lambda f:f(f))(lambda f:f(f))

recursive

Posted 2014-02-17T08:57:34.803

Reputation: 8 616

4A lambda calling itself seems to violate part of the rules though (i.e. "Not allowed to use an obvious recursion.") – Mike Pennington – 2014-02-18T10:49:05.253

1

C#

  public static int i
  {
      set { i = value; }
  }
  static void Main(string[] args)
  {
      i = 0;
  }

Abhi.Net

Posted 2014-02-17T08:57:34.803

Reputation: 119

1obvious recursion. Same as int i() { return i(); } – Reactgular – 2014-02-18T23:01:34.763

1

Common problem in a Rails model

after_save :bump_version

# a lot of code....

private

def bump_version
  create_new_version_record
  update_attribute(:version, version+1)
end

bbozo

Posted 2014-02-17T08:57:34.803

Reputation: 167

1

Flash AS3

public class Work extends Sprite
{
    public function Work()
    {
        doIt();
    }

    private function doIt():void
    {
        noYouDoIt();
    }

    private function noYouDoIt():void
    {
        arguments.callee();
    }
}

Ilya Gazman

Posted 2014-02-17T08:57:34.803

Reputation: 569

1

Netware:

echo hello > file
cat file >> file

I discovered this (but did not use it) many decades ago. I mentioned it to someone, who did it on a Netware share. The share had no limits, and was also used for scratch space by the netware server itself.

The server filled with this one file end-to-end-to-end, crashed (due to running out of diskspace), and couldn't be brought back up until the file was removed. The file, of course, couldn't be removed until the server was running.

AMADANON Inc.

Posted 2014-02-17T08:57:34.803

Reputation: 181

1what happened to your friend and how was the issue bypassed then? – masterX244 – 2014-02-18T20:35:08.807

It happened at a polytech. They admins called me on the carpet, and I said I discovered the flaw, and (truthfully) that I didn't do it, and that I didn't know who did (also truthfully - we were in a class, many people overheard it; I don't think my friend did it). It took the admins several hours to fix the problems. I was not asked to help, of course. – AMADANON Inc. – 2014-02-18T21:39:41.200

@masterX244: obvious bypass is to boot from another media, then access this disk and delete the file. – Mooing Duck – 2014-02-20T01:17:29.680

Netware used their own proprietary filesystem. – AMADANON Inc. – 2014-02-20T20:21:20.260

1

Javascript

Tested in Chrome:

var a = Array(10000000);
(function(){}).apply(this, a);

svidgen

Posted 2014-02-17T08:57:34.803

Reputation: 311

1

C#

public abstract class A
{
  public int X {get { return -1; }}      
  public virtual string Value(){ return "A"; }
}

public class B : A
{
  public new int X {get{ return 42; }}
  public override string Value() { return "B"; }
}

public class C : B
{
  // no recursion; returns -1      
  public int XFromA {get { return ((A)this).X; }}

  // no recursion; returns 42  
  public int XFromB {get { return ((B)this).X; }}

  // no recursion; returns "B"
  public override string Value() { return base.Value(); }

  // StackOverflowException
  public override string Value() { return ((A)this).Value(); }
}

mdisibio

Posted 2014-02-17T08:57:34.803

Reputation: 111

Technically it's still quite obvious because it is technically calling itself, just with an added bit of anonymity. – Pharap – 2014-02-23T02:18:13.203

Just for clarification, the extra level of inheritance is the point of this example. Any class can "cast" itself to its base parent by using the base keyword. But what if it needs to cast itself to its grandparent? Its also possible to use the this keyword in a cast to an interface. So, perhaps I am not a sharp as others reading this, but the syntax seemed quite natural to me, and I had to write several experimental tests to pinpoint the source of the Stackoverflow that caught me by surprise. If it was that obvious, I would have expected the compiler to have caught it. – mdisibio – 2014-02-24T17:11:15.013

I've also added additional code to show that casting the this keyword to a parent or grandparent is not in and of itself the cause of the recursion...when I originally used this code, it was this fact that caused me to think: "that's wierd..." – mdisibio – 2014-02-24T17:42:59.523

1

C

void main()
{
    while(1)
        *(char*)alloca(1000)=0;
}

Funnily, without =0 it will rotate indefinitely because it'll just subtract stack pointer without causing any stack accesses.

Ruslan

Posted 2014-02-17T08:57:34.803

Reputation: 1 283

1

Haskell

import Control.DeepSeq
makeFunc n = \input -> (newfunc input) `deepseq`
    unlines [ "Function number "++(show n)++"was called with "++input
            , "Now calling the next function."
            , newfunc input]
            where
                newfunc=makeFunc (n+1)

main=putStrLn ((  makeFunc (0::Double)  ) "Input")

In this, each function creates a new one, and calls it. Note that this is no recursion, in that no function call itself.

PyRulez

Posted 2014-02-17T08:57:34.803

Reputation: 6 547

what language?; – masterX244 – 2014-02-19T19:45:57.513

Sorry, I changed it, and accidentially deleted the header. – PyRulez – 2014-02-19T19:46:35.757

derps happen sometimes, no issue; thats why i just asked and didnt said something not so friendly – masterX244 – 2014-02-19T19:47:27.223

1

excel vba

Private Sub Worksheet_Change(ByVal Target As Range)
[a1] = 1
End Sub

place code into any worksheet

stack will overflow (in vba, displayed as an out of memory error) as each change to the worksheet triggers another change.

SeanC

Posted 2014-02-17T08:57:34.803

Reputation: 1 117

1

Well just since I'm bored.

int main()
{
   char *ptr;
   ptr = &ptr - sizeof(ptr);
   while(1)
      *--ptr = 0;
}

Invokes undefined behavior that trips the guard page the same way a stack overflow does.

Joshua

Posted 2014-02-17T08:57:34.803

Reputation: 3 043

1

Vim

:se maxf<tab>=0<CR>
:help<CR>

Produces E132: Function call depth is higher than 'maxfuncdepth', vim's equivalent of a stack overflow. (Several times, actually)

Trevor Powell

Posted 2014-02-17T08:57:34.803

Reputation: 111

This works by reducing VimL's stack size and then invoking a simple command. It'd also be possible to achieve similar errors using any standard recursion approach. – Trevor Powell – 2014-02-20T07:07:30.150

1

ANS Forth:

0 >in 2dup ! !

which leads to:

$ gforth
Gforth 0.7.0, Copyright (C) 1995-2008 Free Software Foundation, Inc.
Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license'
Type `bye' to exit
0 >in 2dup ! !                                          
:1: Stack overflow
0 >in 2dup >>>!<<< !
Backtrace:
$B71DF6EC r> 
$B71D34A4 perform 
$B71DD654 (search-wordlist) 
$3 
$0 
$B71DD734 (vocfind) 
$B71D34A4 perform 
$B71D351C (search-wordlist) 
$B71D3FF4 find-name 

In fact, the 2nd ! is never executed.

>in is an integer variable that contains the current position within the input line, the program attempts to write zero to >in two times, but after the first write (!) the input pointer is reset to the start of input line, and the 2nd pair of values is left on the stack...

18446744073709551615

Posted 2014-02-17T08:57:34.803

Reputation: 111

whats the black magic? cant get behind it somehow – masterX244 – 2014-02-20T11:33:28.647

the 1st ! (store) sets the input pointer >in to the beginning of the line. After executing !, the interpreter begins to interpret the line from the very beginning. So anything ending with 0 >in ! is an endless loop. To get a stack overflow, we need to leave something on the stack. I did 2dup, it leaves an extra copy of 0 and the address of >in. And the 2nd ! is never executed because >in gets reset before the interpreter can reach it. – 18446744073709551615 – 2014-02-20T11:48:01.170

Note that after declaring variable x the code 2 x 2dup ! ! (in C it would be x = x = 2;) is absolutely valid, although stupid. – 18446744073709551615 – 2014-02-21T05:05:42.680

1

Another one!

Ruby

class Foo
  def method_missing *args, &block
    foo
  end
end

Foo.new.stack_overflow!
SystemStackError: stack level too deep
        from /home/bbozo/.rvm/rubies/ruby-1.9.3-p286/lib/ruby/1.9.1/irb/workspace.rb:80
Maybe IRB bug!

bbozo

Posted 2014-02-17T08:57:34.803

Reputation: 167

nice one :) especially when the error is spitted in IRB :) – masterX244 – 2014-02-20T14:06:37.990

1

C#

This will stack overflow the CLR I think, and report that type could not be loaded.

public struct Titan 
{
    public Pluto Data { get; set; }
}

public struct Pluto 
{
    public Titan Data { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        //System.TypeLoadException was unhandled
        //Message="Could not load type 'ConsoleApplication1.Titan' from assembly 'ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'."
        //Source="ConsoleApplication1"
        //TypeName="ConsoleApplication1.Titan"
        //StackTrace:
        //     at ConsoleApplication1.Program.Main(String[] args)
        //     at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
        //     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
        //     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
        //     at System.Threading.ThreadHelper.ThreadStart()
        Titan t;
    }
}

ja72

Posted 2014-02-17T08:57:34.803

Reputation: 437

The JIT might optimize the statement away if it is not used. That is what I had a WriteLine() statement. – ja72 – 2014-02-24T00:18:32.143

1

C: "Hello World" format

#include <stdio.h>
int main(){
    (*printf+285)("Hello World\n");
}

This is actually a recursive call that fails when the stack get too big, but it is definitely not an obvious one.

Kevin

Posted 2014-02-17T08:57:34.803

Reputation: 3 123

1

PHP

$a = array('call_user_func_array', &$a);
$a[0]($a[0], $a);

Process exited with code 139.

Compatible from 4.3 to 5.6

sectus

Posted 2014-02-17T08:57:34.803

Reputation: 111

1

(C)Python

eval("f("*99+")"*99)

Produces:

s_push: parser stack overflow
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    eval("f("*99+")"*99)
MemoryError

Bakuriu

Posted 2014-02-17T08:57:34.803

Reputation: 781

1

Python

>>> class C:
...     def __setattr__(self, k, v):
...             self.k = v
...
>>> C().x = 10
...
  File "<stdin>", line 3, in __setattr__
RuntimeError: maximum recursion depth exceeded while calling a Python object

__getattribute__ will also do this in a similar way.

abhink

Posted 2014-02-17T08:57:34.803

Reputation: 11

1

Haskell

I'm surprised nobody posted this already... Maybe it's too obvious?

data Foo = Bar

instance Eq Foo where

main = print (Bar == Bar)

Naturally, Bar == Bar should evaluate to True. So this program should just print "True" and then exit. However, that's not what the empty instance Eq Foo declaration does. ;-)

MathematicalOrchid

Posted 2014-02-17T08:57:34.803

Reputation: 1 451

1

Java

StackOverflowError before main is even executed. No recursive functions required, good old initializers. Also one of the shortest Java programs:

public class _ { static { new _(); } { new _(); } public static void main(String[] _) {}}

Make sure this class isn't referenced anywhere in the codebase or you will get a StackOverflowError on load. Which also makes this really easy to hide anywhere.

Jyro117

Posted 2014-02-17T08:57:34.803

Reputation: 111

1

JAVA

"B" overrides "foo()", but invokes "super.foo()". Because the overridden "foo()" in "A" is invoked by an instance of "B", the "this" reference is pointing to "B", not "A". Therefore, when I create another instance of "this", another "B" object is created.

public class Main {  
  public static void main(String[] args) {
    new B();
  }

   static class A {       
        void foo() { 
            try {
                this.getClass().newInstance();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }


    static class B extends A {
        B() { foo(); }

        void foo() { super.foo(); }
    }
}

usdxile

Posted 2014-02-17T08:57:34.803

Reputation: 111

Don't forget to explain (in your answer) how your solution works. – Justin – 2014-02-23T06:20:45.390

1

Scheme

((lambda (x) (x x)) (lambda (x) (+ 1 (x x))))

I claim this is not an obvious recursion.

Jonathan Cast

Posted 2014-02-17T08:57:34.803

Reputation: 111

after some university stuf that one is now obvious as hell for me – masterX244 – 2015-05-01T16:38:05.317

1

A few months ago I ran into this stack overflow in C#, which took me a significant amount of time to track and figure out what was going on. Assuming you have a C# application with Aspose PDF installed:

Aspose.Pdf.Generator.Pdf pdf = new Pdf();
pdf.HtmlInfo.CharSet = "UTF-8";
pdf.BindHTML("<div><img src=\"myImage.jpg\" alt=\"broken!\" /></div>");
pdf.HtmlInfo.ImgUrl = @"C:\users\me\pictures";
pdf.Save(@"c:\output.pdf");

If "myImage.jpg" is more than about twice as tall as it is wide, the image will overflow the generated PDF page, and somewhere in obfuscated code this results in a stack overflow.

Steven Hunt

Posted 2014-02-17T08:57:34.803

Reputation: 111

bugs outside the own code are the weirdest to locate :P; but nice find – masterX244 – 2014-02-26T20:12:32.040

1

Java

This code causes StackOverflowError on Oracle's JRE/JDK and OpenJDK. Basically, any JVM that uses the reference implementation for the class library.

import java.util.regex.*;
import java.text.*;

class G21114 {
    public static void main(String args[]) {
        StringBuffer buf = new StringBuffer();
        int c = 0;

        for (int i = Character.MIN_CODE_POINT; i < Character.MAX_CODE_POINT; i++) {
            if (Character.isDefined(i) && Character.getType(i) != Character.SURROGATE) {
                int codePoint[] = {i};
                String s = new String(codePoint, 0, codePoint.length);

                if (!Normalizer.normalize(s, Normalizer.Form.NFD).equals(s)) {
                    buf.append(s); buf.append(s); buf.append(s);
                    buf.append('a');
                    buf.append(s); buf.append(s);
                    c++;

                    if (c >= 300) break; // Don't need too many
                }
            }
        }

        System.out.println(buf.length());

        // try-catch to clearly show what is thrown
        try {
            Pattern.compile(buf.toString(), Pattern.CANON_EQ);
        } catch (PatternSyntaxException e) {
            System.out.println(e.getClass());
        } catch (Error e) {
            System.out.println(e.getClass());
        }
    }
}

This is based on the fact that the reference implementation implements the Pattern.CANON_EQ (canonical equivalence) mode by modifying the input string to create alternation between all the possible decompositions. The string is then compiled as per normal.

The construction works well on a single character, but if there are multiple decomposable character in a row, the construction goes amok and doesn't close non-capturing groups (?:regex) properly. Look at this bug report for the test case.

However, to cause StackOverflowError, the parentheses don't need to be balanced. The combination of letters I chose above happen to produce a series of many opening parentheses, which cause the recursive descent parser in Pattern class to exhaust the stack. The underlying cause is similar to ɲeuroburɳ's answer. However, the code above is more discrete in causing the StackOverflowError and depends on internal implementation of Pattern class.

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

Posted 2014-02-17T08:57:34.803

Reputation: 5 683

1

Java

public class Temp {
    public static void main(String[] args) throws Exception {
        Temp.class.getMethod("main", String[].class).invoke(null, new Object[]{null});
    }
}

Gives a bunch of weird stack traces and exceptions

  • InvocationTargetException once with a gazillion times 'caused by InvocationTargetException'
  • InvocationTargetException another gazillion times without stack trace, only ... 1024 more
  • finally ending in StackOverflowError

Also posted in Call a method without calling it

Mark Jeronimus

Posted 2014-02-17T08:57:34.803

Reputation: 6 451

1

Lua:

setmetatable(_ENV, {__newindex = function(x, y) z = y; end});

test="Hello world!"

buildist

Posted 2014-02-17T08:57:34.803

Reputation: 11

2How does it work? – None – 2014-03-02T02:52:43.747

@user2509848 it adds a metatable on the global environment. When test=... is executed, the __newindex method is called, since there's no test in the environment. Then the method does z=..., and since z isn't in the environment too, the recursion happens. Another thing to note, is that the __newindex is executed in a synthesized stack frame (unlike a usual frame which is created upon a regular funicton call), and when those are abused, a C stack overflow occurs. – mniip – 2014-03-02T17:27:02.760

1

Tcl

interp r {} 1
a

Uses the same trick that python uses (recursionlimit).
Calling a will result in a call to unknown which executes a lot of other stuff (which will fail)

And here an other one:

proc unknown {args} a
a

Johannes Kuhn

Posted 2014-02-17T08:57:34.803

Reputation: 7 122

1

Rant

[?[src]]

Allow me to explain.

[src] is a function that returns the source code of the current state object. Metapatterns ([?...]) generate their own source code, so the return value is different when [src] is called inside as opposed to outside. This is where things get rather weird...

When the code is executed, the metapattern generates a source. It calls [src], which returns the metapattern's source code, which is just [src]. It jumps back to the original scope with this new code on the stack, and runs it again. This calls [src], which returns [?[src]]. When this is executed, another metapattern is created. It generates the same code, until the entire allotted stack space is used up and all hell breaks loose.

Basically, the flow of the program looks like this:

  • [?[src]]
    • [src]
      • [?[src]]
        • [src]
          • [?[src]]
            • ...

... where indent depth represents stack size.

Try it online!

Berkin

Posted 2014-02-17T08:57:34.803

Reputation: 61

1

Shell and HQ9+

Assumes that there is an HQ9+ interpreter called hq9

crash_things.sh:

hq9 $1 | crash_things

runs recursively, exits when the output is not a valid HQ9+ program.

evil_code.sh:

hq9 QQ | crash_things

messes it up because the code doubles in length every time.

Lucas

Posted 2014-02-17T08:57:34.803

Reputation: 665

0

Frege

Type this in the REPL at try.frege-lang.org

> foldr (+) 0 [1..]

Ingo

Posted 2014-02-17T08:57:34.803

Reputation: 101

0

Delphi / Object Pascal

Not exactly weird, but technically deprecated and certainly without recursion.

  raise EStackOverflow.Create('Without recursion'); // deprecated warning

This raises the same stack overflow exception that would be raised by an actual stack overflow. Compiling the code results in [dcc32 Warning]: W1000 Symbol 'EStackOverflow' is deprecated warning because the EStackOverflow class is defined in System.SysUtils as deprecated presumably with the intention that it never be actually raised, but it is defined to make it easier to trap and handle a Stack Overflow (despite the fact you really can't do much to recover from a stack overflow).

You could suppress the warning by wrapping it in a compiler directive.

Jim McKeeth

Posted 2014-02-17T08:57:34.803

Reputation: 297

"I.e, avoid boring obvious answers like this:

throw new StackOverflowError(); // Valid, but very boring and downvote-deserving." – Pharap – 2014-02-23T02:10:14.570

0

Python

class I:
    def __init__(self, kids=[]):
        self.kids=kids
    def allkids(self):
        for ii in self.kids:
            ii.allkids()
jj = I()
jj.kids.append(I())
jj.allkids()

It dumps when you run it because of a mutable default argument

  ... more here ...
  File "foo.py", line 6, in allkids
    ii.allkids()
  File "foo.py", line 6, in allkids
    ii.allkids()
RuntimeError: maximum recursion depth exceeded
[mpenning@tsunanmi]$

Mike Pennington

Posted 2014-02-17T08:57:34.803

Reputation: 103

0

Java again.

Using too many parameters this time

public class M
{

    public static final int maxmethods=1024;
    public static void main(String[]a) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        StringBuffer paramvals = new StringBuffer();
        StringBuffer paramdecls = new StringBuffer();
        StringBuffer paramusages = new StringBuffer();
        String[] methodnames = new String[maxmethods];
        String[] methods = new String[maxmethods];
        int i=0;
        for (; i < maxmethods-1; i++)
        {
            methodnames[i] = "method"+i+"(";
            System.out.println(i);
            if(i<253){
            paramvals.append(i+",");
            paramusages.append("param"+i+",");
            paramdecls.append("int param"+i+",");}
        }
        i=maxmethods-1;
        methodnames[i] = "method"+i+"(";
        paramvals.append(255+"");
        paramusages.append("param"+255);
        paramdecls.append("int param"+255);
        for (int j = 0; j < methodnames.length-1; j++)
        {
            methods[j] = "public static void "+methodnames[j]+paramdecls+")\n{\n"+methodnames[j+1]+paramusages+");\n}";
        }
        methods[maxmethods-1] = "public static void "+methodnames[maxmethods-1]+paramdecls+")\n{\nSystem.out.println(\"This shouldnt be reached\");\n}";
        //fuckyou java
        StringBuilder finaL = new StringBuilder();
        finaL.append("public class F{\npublic static void main(String[]a){System.out.println(\"NOPPE\");}\n\nstatic{helper();}\n"+
                "public static void helper(){method0("+paramvals+");\n}\n//#######################################################+\n");
        for (String method : methods)
        {
            finaL.append(method);
        }
        finaL.append("}");
        new FileWriter(new File("F.java")).write((finaL+"").toCharArray());//Dump of srcfile generated
        EU c2 = new EU("F", finaL+"");
        JavaCompiler c = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager f = c.getStandardFileManager(null,null,null);
        c.getTask(null, f, null, null, null,Arrays.asList(new EU[]{c2})).call();
        //System.out.print(new File("").toURI().toURL());
        URLClassLoader u = new URLClassLoader(new URL[]{new File("").toURI().toURL()});
        Class fc = u.loadClass("F");
        fc.getMethod("helper", null).invoke(null, null);    
    }
        public static class EU extends SimpleJavaFileObject {
           final String code;

           EU(String name, String code) {
               super(URI.create("string:///" + name.replace('.','/') + JavaFileObject.Kind.SOURCE.extension),
                     JavaFileObject.Kind.SOURCE);
               this.code = code;
           }
           @Override
           public CharSequence getCharContent(boolean ignoreEncodingErrors) {
               return code;
           }
       }
}

generated file is dumped in workdirecotry used while running; no endless recursion inside :P runtime compilation ftw :)

Edit: moved the method count to a constant

masterX244

Posted 2014-02-17T08:57:34.803

Reputation: 3 942

0

Python

>>> def foo( N ):
    root = list()
    nest = root
    for i in range(N):
        nest.append( list() )
        nest = nest[0]
    return root

>>> nested(999)

Traceback (most recent call last):
  File "<pyshell#184>", line 1, in <module>
    nested(999)
RuntimeError: maximum recursion depth exceeded while getting the repr of a list

Abhijit

Posted 2014-02-17T08:57:34.803

Reputation: 2 841

0

Ruby

class Fixnum
  def +(arg)
    self-arg
  end
  def -(arg)
    self+arg
  end
end

reopens the Fixnum class, defines addition as substraction and substraction as addition, then simply do:

3+2

and voila :)

bbozo

Posted 2014-02-17T08:57:34.803

Reputation: 167

Obvious recursion but still funny. – Pierre Arlaud – 2014-02-20T12:58:55.027

Code that redefines numeric operators to return the wrong answer is always suspicious. Your recursive calls to Fixnum#+ and Fixnum#- look obvious to me. – kernigh – 2014-05-13T02:20:21.440

I did this to a friend, it didn't look obvious to him when he opened up a new feature branch and got stack overflow on an addition ^_^ – bbozo – 2014-05-13T05:02:59.090

0

Batch

START http://stackoverflow.com
ECHO STACKOVERFLOW!
PAUSE > NUL

Sorry, I coudln't resist!

It fulfills rule 1 and 2 ;o

Ray

Posted 2014-02-17T08:57:34.803

Reputation: 109

1LOL :) nice bending of the rules :) – masterX244 – 2014-02-26T20:11:44.097

0

Groovy

def getProperty(String p){ p2 }; p

Due to an undefined property, Groovy calls getProperty again.

Will Lp

Posted 2014-02-17T08:57:34.803

Reputation: 797

0

Python 2

Stack overflow caused by printing. Yes, the standard usual printing operation. It's SIGSEGV, not standard RuntimeError in CPython.

print reduce(lambda*s:s,range(100000))

Konrad Borowski

Posted 2014-02-17T08:57:34.803

Reputation: 11 185

0

We can do it with the worlds most convoluted javascript! I think it's a cheat since it is really just "obvious" recursion.

(function(f){
    return new function () {
        for(var i= 1; i<3;i++) {
        (function(i){this[i] =  this[f(i)] || function (arg) {
            return !arg || (this[f(i)] || this[i + 1]).apply(this, [f(arg)]);
    }}.bind(this))(f(i));
        }       
}
})(function(i){return i === 1 ? i : i - 1;})[1](1);

Jordan

Posted 2014-02-17T08:57:34.803

Reputation: 1

0

VB.NET

I found this when I did your basic merge sort when I came across a StackOverFlowError. I was so confuzzled I asked a SO question about it. Without going to the link, can you find the cause? The link. Obviously this sorting algorithm uses recursion, but that is not the cause of the error being thrown.

Runner Class:

Module Module1

    Sub Main()
        dim array = new integer(100){}
        dim random = new Random()
        for i=0 to 100
            array(i) = random.next()
        next
        dim sorter = new MergeSort()
        sorter.sort(array)
    End Sub
End Module

MergeSort Class:

public class MergeSort

    private numbers() as integer
    private helper() as integer

    private number as integer

    public sub sort(values as integer())
        me.numbers = values
        number = values.length
        me.helper = new integer(number) {}
        mergesort(0, number - 1)
    end sub

    private sub mergesort(low as integer, high as integer)
' check if low is smaller then high, if not then the array is sorted
        if (low < high)
  ' Get the index of the element which is in the middle
          dim middle as integer = low + (high - low) / 2
  ' Sort the left side of the array
          mergesort(low, middle)
  ' Sort the right side of the array
          mergesort(middle + 1, high)
  ' Combine them both
          merge(low, middle, high)
        end if
    end sub

    private sub merge(low as integer,middle as integer,high as integer)
    ' Copy both parts into the helper array
        for l = low to high 
          helper(l) = numbers(l)
        next

        dim i as integer = low
        dim j as integer = middle + 1
        dim k as integer = low
    ' Copy the smallest values from either the left or the right side back
    ' to the original array
        while (i <= middle andalso j <= high) 
          if (helper(i) <= helper(j)) 
            numbers(k) = helper(i)
            i+=1
          else 
            numbers(k) = helper(j)
            j+=1
          end if
          k+=1
        end while

    ' Copy the rest of the left side of the array integero the target array
        while (i <= middle) 
          numbers(k) = helper(i)
          k+=1
          i+=1
        end while
    end sub
end class

Luminous

Posted 2014-02-17T08:57:34.803

Reputation: 309

-1

Ruby

puts Time.now

Presumably, someday many millions of years into the future, the current time will become so large that the computer will run out of memory.

OneChillDude

Posted 2014-02-17T08:57:34.803

Reputation: 99

3Surely time grows linearly while memory grows exponentially according to More's law...? – MathematicalOrchid – 2014-02-22T08:50:25.443

3Won't the time just wrap round since technically most time structures are actually integers internally anyway? – Pharap – 2014-02-23T02:25:57.463

-3

The Ackermann function!

Java

public class Ackermann {

   public static long ackermann(long m, long n) {
      if (m == 0) return n + 1;
      if (n == 0) return ackermann(m - 1, 1);
      return ackermann(m - 1, ackermann(m, n - 1));
   }

   public static void main(String[] args) {
      long M = Long.parseLong(args[0]);
      long N = Long.parseLong(args[1]);
      System.out.println(ackermann(M, N));
   }
}

(Shamelessly copied from http://introcs.cs.princeton.edu/java/75universality/Ackermann.java.html)

 % java Ackermann 3 8
 2045
 % java Ackermann 3 9
 StackOverflowError

Thorbjørn Ravn Andersen

Posted 2014-02-17T08:57:34.803

Reputation: 95

2This is obvious recursion, so I think this is not acceptable according to the rules. – svick – 2014-02-18T17:18:47.170

-3

C

#include <stdio.h>

int main()
{
   main();
   return 0;
}

Charan

Posted 2014-02-17T08:57:34.803

Reputation: 1

This question is about "weird". Your answer doesn't seem very interesting and is not likely to give you upvotes. – user12205 – 2014-02-24T13:14:06.197

please add title of the programming language (in this case c) – Elisha – 2014-02-24T13:52:46.623

You can optimize by return main(); – Fabricio – 2014-05-12T15:10:45.010