[Question]
  [
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
 
 
Closed 7 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
 
 
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 [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"). 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 :)
  
[Answer]
## 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.
[Answer]
# Python
```
import webbrowser
webbrowser.open("http://stackoverflow.com/")
```
[Answer]
## 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.
[Answer]
## 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.
[Answer]
# 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*](https://codegolf.stackexchange.com/a/10449/9498)
```
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>
[Answer]
# C
Quite easy:
```
int main()
{
    int large[10000000] = {0};
    return 0;
}
```
[Answer]
# 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.
[Answer]
I was frustrated by the fact that java 7 and java 8 are immune to my evil code in [my previous answer](https://codegolf.stackexchange.com/a/21121/3755). 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"
```
[Answer]
## JavaScript
```
window.toString = String.toLocaleString;
+this;
```
[Answer]
# 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.
> 
> 
> 
[Answer]
# 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.
[Answer]
# 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...
[Answer]
# Java
A nice one from [Java Puzzlers](http://rads.stackoverflow.com/amzn/click/032133678X). 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.
> 
> 
> 
[Answer]
# LaTeX
```
\end\end
```
The input stack overflows because `\end` repeatedly expands itself in an infinite loop, as explained [here](https://tex.stackexchange.com/questions/124423/end-end-causes-tex-capacity-exceeded).
TeX fails with a `TeX capacity exceeded, sorry [input stack size=5000]` or similar.
[Answer]
# BF
Will eventually overflow the stack, just depends how long the interpreter makes the stack...
```
+[>+]
```
[Answer]
## 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>
[Answer]
**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.
[Answer]
## 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.
> 
> 
> 
[Answer]
# 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(2*n*) time, and *n* is the size of the stack (usually 1024). 
From [Java Puzzlers](http://javapuzzlers.com) #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.
> 
> 
> 
[Answer]
# 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.
[Answer]
# 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;
    }
}
```
[Answer]
# 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
```
[Answer]
# 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](https://i.stack.imgur.com/LGPLc.png)
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.
[Answer]
## 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)
```
[Answer]
## 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]
```
[Answer]
# 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.
[Answer]
## 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>>>>();
    }
}
```
[Answer]
## 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.
[Answer]
# 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.
[Answer]
## C#
wrongly implemented property getter
```
class C
{
   public int P { get { return P; } }
}
static void Main()
{
   int p = new C().P;
}
```
]