144
votes
\$\begingroup\$

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

\$\endgroup\$
19
  • 14
    \$\begingroup\$ I tend to produce by navigating to stackoverflow.com, though I have been known to query 'stack overflow' on my search engine of choice. \$\endgroup\$
    – OJFord
    Commented Feb 17, 2014 at 13:19
  • 21
    \$\begingroup\$ Use Internet Explorer. A sure way to catch one :) \$\endgroup\$
    – asgoth
    Commented Feb 18, 2014 at 17:48
  • 64
    \$\begingroup\$ The 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). \$\endgroup\$ Commented Feb 18, 2014 at 20:32
  • 3
    \$\begingroup\$ I'm partial to this method: joelonsoftware.com/items/2008/09/15.html \$\endgroup\$
    – robert
    Commented Feb 19, 2014 at 13:10
  • 11
    \$\begingroup\$ Drive a Toyota (Hey, wait a minute, my car is a Toyota...) \$\endgroup\$
    – r3mainer
    Commented Feb 22, 2014 at 1:08

116 Answers 116

7
votes
\$\begingroup\$

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.
\$\endgroup\$
11
  • 2
    \$\begingroup\$ Isn't that an obvious recursion though, if my memory of how AWT works is not altered? \$\endgroup\$ Commented Feb 17, 2014 at 9:47
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Justin
    Commented Feb 17, 2014 at 9:48
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Justin
    Commented Feb 17, 2014 at 9:53
  • 2
    \$\begingroup\$ @masterX244 But it's basically like your second example, except the methodA is "hidden" and you're not the one to have programmed it. \$\endgroup\$ Commented Feb 17, 2014 at 10:16
  • 2
    \$\begingroup\$ @ArlaudPierre What you are looking for is un-downvoted. :-) \$\endgroup\$
    – Justin
    Commented Feb 17, 2014 at 10:23
6
votes
\$\begingroup\$

JavaScript - not a single expression

{{{{{{{{{{{{{{{{{{{{{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• \$\begingroup\$ 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. \$\endgroup\$ Commented Feb 26, 2014 at 11:47
  • \$\begingroup\$ The Firefox console returns: InternalError: too much recursion \$\endgroup\$
    – bwDraco
    Commented Oct 2, 2014 at 3:37
5
votes
\$\begingroup\$

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;
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ nice way :) funnily how java fails on hashcoding on a hashset with the set added ti itself 2x... \$\endgroup\$
    – masterX244
    Commented Feb 18, 2014 at 8:26
5
votes
\$\begingroup\$

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);
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ +1 I like the idea of using an [FieldOffset] attribute. \$\endgroup\$ Commented Feb 20, 2014 at 15:38
4
votes
\$\begingroup\$

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.

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

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.

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

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>
\$\endgroup\$
4
votes
\$\begingroup\$

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; }
}
\$\endgroup\$
2
  • \$\begingroup\$ 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 \$\endgroup\$
    – masterX244
    Commented Feb 18, 2014 at 13:29
  • \$\begingroup\$ See this paper: research.microsoft.com/en-us/um/people/akenn/generics/… \$\endgroup\$ Commented Feb 18, 2014 at 18:11
4
votes
\$\begingroup\$

C#

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

var stackOverflow = x + y;

(Actual program output may vary)

\$\endgroup\$
3
  • \$\begingroup\$ how does it work? \$\endgroup\$
    – masterX244
    Commented Feb 19, 2014 at 19:00
  • \$\begingroup\$ @masterX244: StackOverflow.com is created by Joel Spolsky and Jeff Atwood. \$\endgroup\$ Commented Feb 20, 2014 at 12:54
  • 1
    \$\begingroup\$ ahhh :) nifty way to reinterpret the question :P +1 for thinking outside the box \$\endgroup\$
    – masterX244
    Commented Feb 20, 2014 at 13:01
4
votes
\$\begingroup\$

EcmaScript 6 (only 19 bytes!):

atob(...Array(9e5))

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

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

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)

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

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

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

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.

\$\endgroup\$
2
  • \$\begingroup\$ What exactly does this do (for us who don't code in C)? \$\endgroup\$
    – Justin
    Commented Feb 20, 2014 at 1:03
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Feb 20, 2014 at 1:14
3
votes
\$\begingroup\$

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      ******
\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – unclemeat
    Commented Feb 17, 2014 at 21:49
  • 1
    \$\begingroup\$ It's funny how stupid the error message looks, like a 90's computer movie error with big letters and spaces and stars. \$\endgroup\$
    – Ray
    Commented Mar 18, 2014 at 13:11
3
votes
\$\begingroup\$

Python

forking isn't recursion, right?

import os
while 1: os.fork()
\$\endgroup\$
4
  • \$\begingroup\$ the fork bong according to python :) \$\endgroup\$
    – Kiwy
    Commented Feb 17, 2014 at 13:49
  • 11
    \$\begingroup\$ fork bong? \$\endgroup\$ Commented Feb 17, 2014 at 19:36
  • 3
    \$\begingroup\$ A fork bomb perhaps?? \$\endgroup\$ Commented Feb 17, 2014 at 21:33
  • \$\begingroup\$ these days, you have to be careful with such words (bb is listening) [sorry, couldn't resist commenting) \$\endgroup\$
    – blabla999
    Commented Feb 19, 2014 at 10:56
3
votes
\$\begingroup\$

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.

\$\endgroup\$
3
votes
\$\begingroup\$

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
\$\endgroup\$
3
votes
\$\begingroup\$

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];
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Damn, beat me to it D: \$\endgroup\$
    – Pharap
    Commented Feb 23, 2014 at 3:19
3
votes
\$\begingroup\$

Lua

Using metatables frequently results in stack overflows :

a=setmetatable({},{__index=function(t,k)return t[k]end})
print(a[1]) -- index this table.
\$\endgroup\$
3
votes
\$\begingroup\$

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
    
\$\endgroup\$
3
votes
\$\begingroup\$

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 > 
\$\endgroup\$
1
  • \$\begingroup\$ This recursion is obvious. \$\endgroup\$
    – kernigh
    Commented May 13, 2014 at 2:02
3
votes
\$\begingroup\$

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
\$\endgroup\$
3
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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

\$\endgroup\$
0
2
votes
\$\begingroup\$

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!");
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ I like how some of these answers are obvious it was discovered once as a bug. +1 Nice one. \$\endgroup\$
    – Reactgular
    Commented Feb 18, 2014 at 23:03
2
votes
\$\begingroup\$

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

\$\endgroup\$
2
votes
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Oh I like this one! \$\endgroup\$
    – Jason C
    Commented Feb 18, 2014 at 3:44
  • \$\begingroup\$ @Jason C: if you dump that source file generated and run it through javac manually it still stackoverflows :P \$\endgroup\$
    – masterX244
    Commented Feb 18, 2014 at 8:19
2
votes
\$\begingroup\$

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)

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I 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. \$\endgroup\$ Commented Feb 19, 2014 at 13:43
  • \$\begingroup\$ @nhahtdh Brilliant! I didn't know that! \$\endgroup\$
    – Vereos
    Commented Feb 19, 2014 at 14:12
2
votes
\$\begingroup\$

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,

                ... ;
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ 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) \$\endgroup\$
    – masterX244
    Commented Feb 19, 2014 at 18:58
2
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ +1 for something new. But I really doubt anyone would run into this in actual usage. \$\endgroup\$ Commented Feb 20, 2014 at 13:00
  • \$\begingroup\$ @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. \$\endgroup\$
    – Pharap
    Commented Feb 23, 2014 at 1:41

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