Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write a program that throws a StackOverflow Error or the equivalent in the language used. For example, in java, the program should throw java.lang.StackOverflowError.

You are not allowed to define a function that calls itself or a new class(except the one containing main in java). It should use the classes of the selected programming language.

And it should not throw the error explicitly.

share|improve this question
3  
I don't understand "use the classes of the selected programming language" – Prince John Wesley Jan 4 at 15:07
1  
Is it ok to define a function that calls inner function like this def s{def t=s;t} ? – Prince John Wesley Jan 4 at 15:10
5  
In most languages, classes are only a special kind of data structure, not the center of the universe. Many don't even have such a thing. – leftaroundabout Jan 4 at 21:42
1  
The funny thing here is that languages that require tail recursion elimination (and implementations that support it when the languages does not require it)---which are in a very real sense better---are at a disadvantage on this. TwiNight's answer links to the version of this that exists on Stack Overflow from the early days. – dmckee Jan 4 at 22:13
1  
From the java doc: Thrown when a stack overflow occurs because an application recurses too deeply. docs.oracle.com/javase/6/docs/api/java/lang/… – anakata Apr 9 at 16:24
show 3 more comments

33 Answers

1 2

Lua

function b()b()end b() --stack overflow

Alternatively,

a={}setmetatable(a,{__index=function()return a.a end})a(a.a) --C stack overflow
share|improve this answer
"You are not allowed to define a function that calls itself". That aside, what language is this? – Peter Taylor Jan 15 at 18:43
@PeterTaylor: These are two separate Lua programs. – PleaseStand Jan 15 at 19:16
The first one is syntactically broken. Try a=function(b)b(b)end;a(a) for 25 characters. It defines a function that calls its parameter, passing itself as the parameter. Certainly evades the tail recursion optimization, and skirts the spirit of not writing a directly recursive function. – RBerteig Apr 17 at 21:44

Java(123 chars)

public class Overflow {
    static int[][][][][] a = new int[99][99][99][99][99];
    public static void main(String[] args) {}
}

This could probably be trimmed down quite a bit, but I prefer a buffer of ruination.

Technically, this won't SO everybody, but most people don't give the JVM 35GB of RAM.

share|improve this answer

VBScript, 101 characters

Not the smallest script, but created as a proof of concept

i=2
s="sub[2](b):i=i+1:d=replace(b,i-1,i):execute d:call getref("""&i&""")(d):end sub"
execute s
[2]s

This code creates new named functions on the fly by executing a string that creates a function and giving the new function this string as a parameter. The function creates a new function and calls it. Results in a Microsoft VBScript runtime error: Out of stack space: 'execute' error.

share|improve this answer

In C

void main()
{
    main();
}

This will cause Stack Overflow

share|improve this answer
4  
"You are not allowed to define a function that calls itself". – hammar Mar 26 at 23:26

A bunch in the same style:

Python, 30

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

Javascript, 38

(function(x){x(x)})(function(y){y(y)})

Lua, 44

(function(x) x(x) end)(function(y) y(y) end)
share|improve this answer
In Python x=lambda y:y(y);x(x) is shorter (20 chars). This function is not recursive. x calls any function passed to it as an argument. – AMK Apr 17 at 16:28

C#: 66 (full program)

(full program, not excerpt like other one, although it's based on it)

class A{static int a{get{return a;}} static void Main(){var x=a;}}
share|improve this answer

Tcl, 15 chars

interp r {} 1;a

gives

too many nested evaluations (infinite loop?)

the interp r stands for interp recursionlimit (you can abbreviate subcommands). a calls (because not known) unknown, which calls a lot of other stuff.

share|improve this answer

C#: 106 86 58 46 32

32: Getters can SO your machine easy in C#:

public string a {get{return a;}}
share|improve this answer
1  
No need for setter public int a {get{return a;}} – Mika Kolari Apr 10 at 10:35
2  
This violates the rule "You are not allowed to define a function which calls itself". Admittedly it's hidden behind syntax sugar, but it's still missing the point of the challenge. – Peter Taylor Apr 11 at 13:08
Adding the setter somewhat circumvents the rule, because you now have two functions calling each other. But I wonder: does that still violate the OP's intentions behind this challenge? – Andrew Gray Apr 11 at 13:10
The idea as I understand it is to find some excessively nested recursion in the interpreter or standard API of the language. This might not be too easy in C#. – Peter Taylor Apr 13 at 21:21

Q/k (16 chars)

Not sure if this is in the spirit of the challenge but I don't think it breaks the rules:

s:{f`};f:{s`};f`
share|improve this answer
It's a shame C# requires so much typing, you inspired my answer! – Andrew Gray Apr 8 at 18:59

Python, real stack overflow: 38

a=[];eval("[x "+"for x in a "*800+"]")

Error message:

s_push: parser stack overflow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

Explanation:

[x for x in a for x in a]

is the same as

y = []
for x in a:
    for x in a:
        y.append(x)

so the above eval produces 800 nested for loops :)

share|improve this answer
Ah just noticed that someone else already exploited the parser in a similar, more elegant way: codegolf.stackexchange.com/a/9370/6491 – stefreak Mar 29 at 13:03

Javascript 24 characters

Browser dependent answer (must have access to apply):

eval.apply(0,Array(999999))
  • eval was the shortest global function name that I could find (anyone know of one that is shorter?)
  • apply allows us to convert an array into function parameters, the first parameter being the context of the function (this)
  • Array(999999) will create an array with the listed length. Not sure what the maximum number of arguments is, but it's less than this, and more than 99999

IE9:

SCRIPT28: Out of stack space 
SCRIPT2343: Stack overflow at line: 20 

Chrome 24:

Uncaught RangeError: Maximum call stack size exceeded 

FireFox 18

RangeError: arguments array passed to Function.prototype.apply is too large

Note — Due to the single threaded nature of javascript, infinite loops end up locking the UI and never throwing an exception.

while(1);
for(;;);

Neither of these qualify.

Update — this shaves off three characters:

eval.apply(0,Array(1e7))
share|improve this answer
MDN says that eval is the shortest. – Peter Taylor Jan 23 at 13:30

Groovy (27 chars)

a=[:];b=[a:a];a.b=b;print b

And so it goes:

Caught: java.lang.StackOverflowError
    java.lang.StackOverflowError
share|improve this answer

Python (15 chars)

def f():f()
f()

RuntimeError: maximum recursion depth exceeded

share|improve this answer
"You are not allowed to define a function that calls itself" – aditsu Mar 24 at 10:43

Java - 35

class S{static{new S();}{new S();}}
share|improve this answer

Haskell (GHC, no optimization), 25

main=print$sum[1..999999]

sum is lazy in the total. This piles up a bunch of thunks, then tries to evaluate them all at the end, resulting in a stack overflow.

share|improve this answer

PHP 5.4, 33 characters

for($n=1e5;$n--;)$a=(object)[$a];

This causes a stack overflow when the nested stdClass objects are automatically destroyed:

$ gdb -q php
Reading symbols from /usr/bin/php...(no debugging symbols found)...done.
(gdb) set pagination 0
(gdb) r -nr 'for($n=1e5;$n--;)$a=(object)[$a];'
Starting program: /usr/bin/php -nr 'for($n=1e5;$n--;)$a=(object)[$a];'
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
0x00000000006debce in zend_objects_store_del_ref_by_handle_ex ()
(gdb) bt
#0  0x00000000006debce in zend_objects_store_del_ref_by_handle_ex ()
#1  0x00000000006dee73 in zend_objects_store_del_ref ()
#2  0x00000000006a91ca in _zval_ptr_dtor ()
#3  0x00000000006c5f78 in zend_hash_destroy ()
#4  0x00000000006d909c in zend_object_std_dtor ()
#5  0x00000000006d9129 in zend_objects_free_object_storage ()
#6  0x00000000006dee53 in zend_objects_store_del_ref_by_handle_ex ()
#7  0x00000000006dee73 in zend_objects_store_del_ref ()
#8  0x00000000006a91ca in _zval_ptr_dtor ()
#9  0x00000000006c5f78 in zend_hash_destroy ()
#10 0x00000000006d909c in zend_object_std_dtor ()
#11 0x00000000006d9129 in zend_objects_free_object_storage ()
[...]
#125694 0x00000000006dee53 in zend_objects_store_del_ref_by_handle_ex ()
#125695 0x00000000006dee73 in zend_objects_store_del_ref ()
#125696 0x00000000006a91ca in _zval_ptr_dtor ()
#125697 0x00000000006c5f78 in zend_hash_destroy ()
#125698 0x00000000006d909c in zend_object_std_dtor ()
#125699 0x00000000006d9129 in zend_objects_free_object_storage ()
#125700 0x00000000006dee53 in zend_objects_store_del_ref_by_handle_ex ()
#125701 0x00000000006dee73 in zend_objects_store_del_ref ()
#125702 0x00000000006a91ca in _zval_ptr_dtor ()
#125703 0x00000000006c4945 in ?? ()
#125704 0x00000000006c6481 in zend_hash_reverse_apply ()
#125705 0x00000000006a94e1 in ?? ()
#125706 0x00000000006b80e7 in ?? ()
#125707 0x0000000000657ae5 in php_request_shutdown ()
#125708 0x0000000000761a18 in ?? ()
#125709 0x000000000042c420 in ?? ()
#125710 0x00007ffff5b6976d in __libc_start_main (main=0x42bf50, argc=3, ubp_av=0x7fffffffe738, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffe728) at libc-start.c:226
#125711 0x000000000042c4b5 in _start ()
share|improve this answer
+1 for what must be PHP's second appearance on CodeGolf! – Bojangles Apr 11 at 13:53
//Java's answer...

public class Test
{
    private Test test = new Test();

    public static void main(String[] args)
    {
        new Test();
    }
}
share|improve this answer

Postscript, 7

{1}loop

Eg.

$ gsnd
GPL Ghostscript 9.06 (2012-08-08)
Copyright (C) 2012 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
GS>{1}loop
Error: /stackoverflow in 1
Operand stack:
   --nostringval--
Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   %loop_continue   --nostringval--   --nostringval--   false   1   %stopped_push   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   %loop_continue
Dictionary stack:
   --dict:1168/1684(ro)(G)--   --dict:0/20(G)--   --dict:77/200(L)--
Current allocation mode is local
Last OS error: No such file or directory
Current file position is 8
GS<1>
share|improve this answer

Ruby, 12

eval"[]"*9e3

Gives

SystemStackError: stack level too deep

Presumably system-dependent, but you can add orders of magnitude by bumping the last digit up (not recommended).

Edit for explanation: Similarly to some other examples, this creates a string of [][][]...repeated 9000 times, then evaluates it: the rightmost [] is parsed as a function call to the rest, and so on. If it actually got to the beginning, it would throw an ArgumentError because [] is an object with a [] method that requires one argument, but my machine throws an error a little before the stack is over nine thousand.

share|improve this answer
hmm... crashed IRB :P – Doorknob Mar 22 at 23:35

Java - 115 chars

I think this stays within the spirit of the "no self-calling methods" rule. It doesn't do it explicitly, and it even goes through a Java language construct.

public class S {
    public String toString() {
        return ""+this;
    }
    public static void main(String[] a) {
        new S().toString();
    }
}
share|improve this answer
3  
Well, ""+this is actually ""+this.toString(), so the method calls itself. – True Soft Jan 19 at 8:08

FORTH (13)

BEGIN 1 AGAIN

overflows the value stack

share|improve this answer
: X X ; X (9) must overflow return stack – AMK Jan 18 at 14:45
won't work (X isn't defined while defining the call and that's a self reference/recursion – ratchet freak Jan 18 at 14:50

C -- 34 characters, no libraries

Though competative with Job's answer,

o(){O();}
O(){o();o();}
main(){o();}

violates the spirt of the challenge by showing how to evade the restriction on constructing a simple recursion. You can save 4 character by removing one call from O, but gcc is smart enough to recongnise that if you use -O3.1

The trick is quite general and can be done in fortran 77, too (142 characters):

      program o
      i=j()
      stop
      end
      function j()
      j=k()
      end
      function k()
      k=j()
      k=j()
      end

Again, gcc can optimize away a single call in each.


1 I suppose it inlines one of them and then applys tail recursion elimination. How cool is that!?!.

share|improve this answer
O(){o(o());} saves a character. Replacing O with recursive main call saves more. – ugoren Jan 15 at 7:43

C, 35 characters

main(){for(;;)*(int*)alloca(1)=0;}
share|improve this answer
Why store anything in the assigned space? – Peter Taylor Jan 5 at 17:15
1  
In this case, it's impossible to solve this problem in C. – FUZxxl Jan 6 at 15:41
2  
@dmckee, Not all segmentation faults are stack overflows, but I'd say this one is, since it's the result of exceeding the stack capacity. – ugoren Jan 6 at 19:12
1  
@dmckee, alloca allocates from the stack. – ugoren Jan 6 at 19:15
1  
@PeterTaylor: It probably depends on the implementation but in my case alloca(1) is basically translated to sub $1, %esp so the stack isn't touched. – Job Jan 7 at 14:48
show 10 more comments

Coq

Compute 70000.

70000 is just syntactic sugar for S (S ( ... (S O) ...)) with 70000 S's. I think it's the type checker that causes the stack overflow.

Here's a warning that is printed before the command is executed:

Warning: Stack overflow or segmentation fault happens when working with large
numbers in nat (observed threshold may vary from 5000 to 70000 depending on
your system limits and on the command executed).
share|improve this answer
1  
That might let you think Coq is an incredibly dumb language... funny... – leftaroundabout Jan 6 at 13:01
1  
@leftaroundabout Actually not. The Nat type is a type level peano numeral that must act as if it is a linked list. – FUZxxl Jan 6 at 15:40
1  
@FUZxxl: my comment was not not meant ironically at all. Decide for yourself if you want to include classical logic into that sentence, or prefer to stay constructive... – leftaroundabout Jan 6 at 20:42
1  
@leftaroundabout Oops... sorry. I forgot that the markdown parser always eats those nice &lt;irony&gt;-tags. – FUZxxl Jan 6 at 21:28

Ocaml

let rec f () = ignore (f ())
let () = f()

Ocaml has proper tail calls so the following wouldn't work. We cannot (directly) return the value of the recursive call.

let rec f () = f ()
let () = f()
share|improve this answer
"You are not allowed to define a function that calls itself". – Peter Taylor Jan 15 at 18:43
Huh. I don't know how I managed to miss that. Anyway, I think it's still slightly interesting since ocaml has proper tail calls. – ReyCharles Jan 31 at 12:46

X86 assembly (AT&T), 33 characters

Note that although I'm using the label main as a jump target, this is not a recursive function.

.globl main
main:push $0;jmp main
share|improve this answer
Nice idea: this is a sort of recursion-without-recursion! – Andrea Corbellini Jan 9 at 21:29
using a86: dd 0fdeb60 10 characters! – Skizz Jan 15 at 16:17

Clojure, 12 chars

(#(%%)#(%%))

Running in the repl:

user=> (#(%%)#(%%))
StackOverflowError   user/eval404/fn--407 (NO_SOURCE_FILE:1)
share|improve this answer

Python 2.7 (12 chars)

exec('{'*99)

results in a «s_push: parser stack overflow»

share|improve this answer
3  
I get SyntaxError: unexpected EOF while parsing – moose Jan 14 at 7:15
1  
With exec('{'*101) I get MemoryError – moose Jan 14 at 7:15

Perl 5, 20 characters

while(1){fork&&wait}

This is a "POSIX program" I happen to have expressed in Perl. Each process creates a child process and waits for it to complete; it will most likely hit a "too many processes" limit, which is the multi-process analogue of a stack overflow. The error itself happens to be ignored, but that's just because there is no automatic "throw" in Perl.

I have not actually tested this program as I don't have a machine I care to fork-bomb handy.

share|improve this answer

Python (2.7.3), 35 characters

import sys
sys.setrecursionlimit(1)

This operation itself succeeds, but both script and interactive will immediately throw RuntimeError: 'maximum recursion depth exceeded' afterward as a consequence.

Inspired by elssar's answer.

share|improve this answer
I thought about putting that up as my solution instead, but wasn't sure if the error could be considered a stack overflow. Though, essentially, that is what it is, right? – elssar Jan 5 at 8:25
1 2

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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