Shortest program that throws StackOverflow Error

76

19

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.

True Soft

Posted 13 years ago

Reputation: 1 075

Question was closed 8 years ago

Is this even possible in JS? – Cyoce – 10 years ago

4I don't understand "use the classes of the selected programming language" – Prince John Wesley – 13 years ago

3Is it ok to define a function that calls inner function like this def s{def t=s;t} ? – Prince John Wesley – 13 years ago

12In 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. – ceased to turn counterclockwis – 13 years ago

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 --- ex-moderator kitten – 13 years ago

@PrinceJohnWesley, I wanted to say to use the structures/functions of the programming language, not to define something new; to avoid answers like define a function which calls itself. – True Soft – 13 years ago

I wonder if certain Math Errors in calculators could be called stackoverflows, if so then 99! would be a very short one on my casio – Griffin – 13 years ago

Does a compile-time overflow violate the rules at all? – Andrew Gray – 13 years ago

1

From the java doc: Thrown when a stack overflow occurs because an application recurses too deeply. http://docs.oracle.com/javase/6/docs/api/java/lang/StackOverflowError.html

– jsedano – 13 years ago

Answers

90

Befunge, 1

I don't know Befunge, but...

1

from Stack overflow code golf

TwiNight

Posted 13 years ago

Reputation: 4 187

21Explanation: 1 is a numeric literal that gets pushed to the stack when encountered. In Befunge, control flow wraps around until it encounters an @ to end the program. – histocrat – 13 years ago

6I didn't know there was this question on StackOverflow. I searched only on this site before posting. – True Soft – 13 years ago

31I'm mildly flattered to see my answer here. – Patrick – 13 years ago

4This works in ><> too. – Cruncher – 12 years ago

49

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.

Kevin Reid

Posted 13 years ago

Reputation: 1 693

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 – 13 years ago

2@elssar: I guess there are two ways to overflow the stack: make the used part of the stack larger, or make the unused part of the stack smaller. If you imagine a bucket filling with water, you can overflow it by adding more water, but you can also overflow it by shrinking the bucket. – None – 8 years ago

20

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

ReyCharles

Posted 13 years ago

Reputation: 525

2That might let you think Coq is an incredibly dumb language... funny... – ceased to turn counterclockwis – 13 years ago

1@leftaroundabout Actually not. The Nat type is a type level peano numeral that must act as if it is a linked list. – FUZxxl – 13 years ago

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... – ceased to turn counterclockwis – 13 years ago

2@leftaroundabout Oops... sorry. I forgot that the markdown parser always eats those nice <irony>-tags. – FUZxxl – 13 years ago

19

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

Shmiddty

Posted 13 years ago

Reputation: 1 209

1new shortest in ES6: eval(...Array(9e9)) – Patrick Roberts – 10 years ago

MDN says that eval is the shortest. – Peter Taylor – 13 years ago

1Probably non-standard, throws in Chrome from the console. dir.apply(0,Array(1e7)); – Paul J – 9 years ago

5eval.apply(0,Array(1e6)) saves 3 chars, you can even go with 9e9 at no cost – ThinkChaos – 12 years ago

1apply is a standard ECMAScript feature. There is nothing browser dependent. Unless you are talking about really old browsers, but this wouldn't work in hypothetical Netscape 2 with apply anyway, because Array class doesn't exist in Netscape 2. – Konrad Borowski – 12 years ago

19

Java - 35

class S{static{new S();}{new S();}}

aditsu quit because SE is EVIL

Posted 13 years ago

Reputation: 22 326

Java8 & Eclipse: trying to run this program, no Exception is thrown, sorry... – Luigi Cortese – 10 years ago

1@LuigiCortese I think it only works with java 6 or older – aditsu quit because SE is EVIL – 10 years ago

Didn't OP say no new classes? I don't see a public static void main in there. Or am I just failing to understand Java? – Braden Best – 12 years ago

4@B1KMusic There are no new classes, there's only one class (S). The code uses a static initializer, it throws the SO before the jvm figures out there's no main method. Works with java 6. – aditsu quit because SE is EVIL – 12 years ago

1I understand the static block. But what is the next block ? – Nicolas Barbulesco – 11 years ago

1@NicolasBarbulesco That's an initializer block, it's executed when you construct a new instance. – aditsu quit because SE is EVIL – 11 years ago

17

Python 2.7 (12 chars)

exec('{'*99)

results in a «s_push: parser stack overflow»

Daniel

Posted 13 years ago

Reputation: 1 801

4I get SyntaxError: unexpected EOF while parsing – Martin Thoma – 13 years ago

1With exec('{'*101) I get MemoryError – Martin Thoma – 13 years ago

You need at least 100 to trigger a MemoryError. And that ≠ stack overflow – noɥʇʎԀʎzɐɹƆ – 9 years ago

4In Python2, exec is a statement, so you can just use exec'{'*999 (99 doesn't seem to be enough) – gnibbler – 12 years ago

13

Mathematica, 4 chars

x=2x

$RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>

alephalpha

Posted 13 years ago

Reputation: 23 988

1"You may not define function that calls itself" – Tomas – 12 years ago

13That isn't a function, it's a variable (unless it isn't at all what it looks like). – A.M.K – 12 years ago

You took my idea. – PyRulez – 12 years ago

12

Java - 113 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();
    }
}

Condensed Version:

public class S{public String toString(){return ""+this;}public static void main(String[] a){new S().toString();}}

Joe K

Posted 13 years ago

Reputation: 1 065

9Well, ""+this is actually ""+this.toString(), so the method calls itself. – True Soft – 13 years ago

1@TrueSoft Pretty sure java throws in a StringBuilder object there. toString will likely be called from within there. – Cruncher – 12 years ago

1By the time the compiler and optimizer are done, the toString() method ends up being public java.lang.String toString() { return this.toString(); } – Jonathan Callen – 12 years ago

12

C, 19 bytes

main(){int i[~0u];}

Jens

Posted 13 years ago

Reputation: 291

Doesn't work for me after I manually configured a 4GB stack. – FUZxxl – 10 years ago

@FUZxxl Interesting; are your ints 32 bit? If so, sizeof(i) is 16GB. Does using an ul or ull suffix make a difference? Some systems over-commit memory and only crash if the memory is written to. – Jens – 10 years ago

Nothing accesses the array, so it is not generated and no error. At least initializing or using it is necessary to error. – Karl Napf – 9 years ago

You can golf off 1byte by doing this main(int i[~0u]){} – Albert Renshaw – 9 years ago

@AlbertRenshaw I don't think this works, because the argument declaration is equivalent to int *i and will neither allocate memory nor crash. – Jens – 8 years ago

4@Thomas Yes it is a stack overflow on any machine where local variables are allocated on the stack. Since the C language has no concept of a stack overflow indication (it's all undefined behavior; one of them manifests itself as a segfault), this does fit the original requirement. – Jens – 12 years ago

OK, sorry, accepted. – Tomas – 12 years ago

3it gives main.c:1:16: error: size of array 'i' is negative for me on gcc 4.8.1. The unsigned version main(){int i[~0U];} works. – Csq – 12 years ago

12

Clojure, 12 chars

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

Running in the repl:

user=> (#(%%)#(%%))
StackOverflowError   user/eval404/fn--407 (NO_SOURCE_FILE:1)

David Cabana

Posted 13 years ago

Reputation: 121

This reminds me of the lambda calculus expression (\x.xx)(\x.xx), but I don't know clojure well enough to tell for sure if this is what's happening. I also don't see why the aforementioned expression would result in a stack overflow, so maybe you're doing some trickery with the Y-combinator? This answer interests me and an explanation would be nice. – Zwei – 9 years ago

10

x86 assembly, NASM syntax, 7 bytes

db"Pëý"

"Pëý" is 50 EB FD in hexadecimal, and

_loop:
push eax
jmp _loop

in x86 assembly.

user12487

Posted 13 years ago

Reputation:

10

GolfScript (8 chars)

{]}333*`

Result:

$ golfscript.rb overflow.gs 
golfscript.rb:246:in `initialize': stack level too deep (SystemStackError)
from /home/pjt33/bin/golfscript.rb:130:in `new'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
from /home/pjt33/bin/golfscript.rb:130:in `map'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
from /home/pjt33/bin/golfscript.rb:130:in `map'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
 ... 993 levels...
from (eval):4
from /home/pjt33/bin/golfscript.rb:293:in `call'
from /home/pjt33/bin/golfscript.rb:293:in `go'
from /home/pjt33/bin/golfscript.rb:485

Basically this creates a heavily nested data structure and then overflows the stack when trying to turn it into a string.

Peter Taylor

Posted 13 years ago

Reputation: 41 901

For me, this doesn't throw an error, but outputs [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[""]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] ]]]]]]]]]]]]]]]]] (and so on, output too long for comments) – ProgramFOX – 12 years ago

@ProgramFOX, there will be some value which you can replace 333 with and it will break. 333 was the smallest value which broke for me, but if you have a different version of Ruby (or maybe the same version on a different OS, for all I know) it might handle a different number of stack frames before overflowing. – Peter Taylor – 12 years ago

1Breaks at 3192 on my machine, so 6.? still works without adding characters. – Dennis – 11 years ago

8

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.

histocrat

Posted 13 years ago

Reputation: 20 600

I would have said def f;f;end;f – EMBLEM – 10 years ago

That wouldn't fit the full problem description. And is longer. – histocrat – 10 years ago

hmm... crashed IRB :P – Doorknob – 13 years ago

Which version? ruby 1.9.2 throws “ArgumentError: wrong number of arguments (0 for 1..2)”. – manatwork – 12 years ago

Found an old ruby 1.8.7. There the posted code works as described. – manatwork – 12 years ago

Odd, it works on my 1.8.7, 1.9.2, and 1.9.3. – histocrat – 12 years ago

8

Rebol (11 Chars)

do s:[do s]

Yields:

>> do(s:[do s])    
** Internal error: stack overflow
** Where: do do do do do do do do do do do do do do do do 
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do 
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do...

Though Rebol has functions, closures, and objects...this doesn't define any of those. It defines a data structure, which in the code-as-data paradigm can be treated as code using DO.

We can probe into the question of "what is S" with the REPL:

>> s: [do s]
== [do s]

>> type? s
== block!

>> length? s
== 2

>> type? first s
== word!

>> type? second s
== word!

DO never turns this into a function, it invokes the evaluator in the current environment on the structure.

rgchris

Posted 13 years ago

Reputation: 304

1+1 ... I hadn't noticed that my answer was defining a function and that was against the rules, but edited my answer to use DO...then noticed you'd already submitted that answer. So I just deleted mine, but since I'd written up why this isn't defining an object/function/closure I thought I'd put the explanation into yours. Also I think the do do do do is kind of funny and worth including. :-) Hope that's ok! – HostileFork says dont trust SE – 12 years ago

7

FORTH, 13 bytes

BEGIN 1 AGAIN

overflows the value stack

ratchet freak

Posted 13 years ago

Reputation: 1 334

: X X ; X (9) must overflow return stack – AMK – 13 years ago

won't work (X isn't defined while defining the call and that's a self reference/recursion – ratchet freak – 13 years ago

@ratchetfreak, those control words can only be used in a compile state, so they need to be wrapped in a :...; word definition. That adds at least 6 characters, plus at least 2 more for this to execute as a program. You might be able to do it shorter, but here's an example: : F BEGIN 1 AGAIN ; F. I suggest this because the question asks: "Write a program." Anyways, gave you an upvote for Forth, regardless of char count! :-) – Darren Stone – 12 years ago

7

Common Lisp, 7 characters

#1='#1#

Erik Haliewicz

Posted 13 years ago

Reputation: 401

Beautiful...I was planning to use #1=(#1#) for the terminal and (print #1=(#1#)), but your solution is so much better. – protist – 12 years ago

Actually that doesn't overflow at read time, only when you attempt to print it. So aside from the 1 character difference, yours is no better. – protist – 12 years ago

You're right, just edited that out. I'm not sure if there's a way to cause an overflow at read-time. – Erik Haliewicz – 12 years ago

Actually, #.#1='#1# causes a read-time overflow :-) – Erik Haliewicz – 12 years ago

7

Python - 11 chars

exec'('*999

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

gnibbler

Posted 13 years ago

Reputation: 14 170

Very clever solution. – mbomb007 – 11 years ago

7

Casio Calculator, 11 keypresses

It's quite hard to count bytes/tokens in this "language" - I've given the number of keypresses required, excluding Shift, Alpha (the second shift key) and = at the end - this certainly fits into 1 byte per keypress.

Tested on the fx-85GT PLUS model, which is a standard, non-graphing, "non-programmable" scientific calculator. Other models will work.

Just stack up 11 cube roots:

3√ 3√ 3√ 3√
3√ 3√ 3√ 3√
3√ 3√ 3√

It doesn't even give a syntax error about the missing number under the square root.

This doesn't seem to work with square roots.

Alternatively, repeat cos( 31 times.

Output

Stack ERROR

[AC]  :Cancel
[<][>]:Goto

I believe that this qualifies as a stack overflow. The stack seems to be tiny...

user16402

Posted 13 years ago

Reputation:

I always thought it was called stack error because you "stacked up" too many roots :P – FlipTack – 9 years ago

My Canon calculator gives a stack error with just about any operator (excluding at least +, -, * and /) if it is repeated 25 times or more. For instance, this causes stack error (without syntax error): ((((((((((((((((((((((((( – Steadybox – 9 years ago

7

C, 35 characters

main(){for(;;)*(int*)alloca(1)=0;}

Job

Posted 13 years ago

Reputation: 240

Interestingly enough, on my machine using the latest GCC, there is no stackoverflow. The code compiles down to .L2: jmp .L2, generating an infinite loop that never errors. – David – 11 years ago

@BЈовић Compile with a C89 compiler. – FUZxxl – 10 years ago

@StephenMontgomery-Smith alloca() always allocated on the stack. – FUZxxl – 10 years ago

Why store anything in the assigned space? – Peter Taylor – 13 years ago

@PeterTaylor: Because a segmentation fault is only generated when memory outside the available stack space is accessed. Just calling alloca only decrements the stack pointer. – Job – 13 years ago

1In this case, it's impossible to solve this problem in C. – FUZxxl – 13 years ago

3@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 – 13 years ago

The initial int isn't needed, and you can call alloca within the while() (but assign 1). – ugoren – 13 years ago

1

@dmckee, alloca allocates from the stack.

– ugoren – 13 years ago

@Job: This needs an #include<stdlib.h>, though, I think... but you can use the implicit int return type and just main(){*(int*)alloca(9999999)=0;}. – Ry- – 13 years ago

Or maybe that's not guaranteed to do the trick, but for(;;) instead of while(1) saves the same number of characters. – Ry- – 13 years ago

I improved my answer a bit, thanks to everyone for the tips! – Job – 13 years ago

@ugoren: I don't really understand what you mean... – Job – 13 years ago

@minitech: That's not guaranteed to cause a stack overflow. – Job – 13 years ago

@job - I see you did remove the int. My other suggestion is no longer needed (while(*(int*)alloca(1)=1); is the same length). – ugoren – 13 years ago

Thinking about this more: are you sure it's necessary to store something in the assigned address in order to access unavailable stack space? Unless alloca is inlined it seems to me that the stack frame used to call it should move one byte further each time. – Peter Taylor – 13 years ago

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 – 13 years ago

error: ‘alloca’ was not declared in this scope – BЈовић – 13 years ago

FreeBSD allocates on the stack. Linux allocates in the data area. So it depends which OS you use. – Stephen Montgomery-Smith – 12 years ago

Also, in some OS you have to assign the allocated space a value, because the OS won't actually allocate the space until it is needed. But maybe that's just for malloc. – Stephen Montgomery-Smith – 12 years ago

6

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>

luser droog

Posted 13 years ago

Reputation: 4 535

6

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.

Joey Adams

Posted 13 years ago

Reputation: 9 929

i always thought sum was implemented using foldl'. isn't it? – proud haskeller – 11 years ago

Alas, it isn't: http://hackage.haskell.org/package/base/docs/src/Data-List.html#sum

– Joey Adams – 11 years ago

6

LaTeX: 8 characters

\end\end

This is the same code used in this answer. Essentially, the \end macro expands itself repeatedly, resulting in a stack overflow: TeX capacity exceeded, sorry [input stack size=5000]. A more detailed explanation can be found here.

bwDraco

Posted 13 years ago

Reputation: 571

5

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

PleaseStand

Posted 13 years ago

Reputation: 5 369

2+1 for what must be PHP's second appearance on CodeGolf! – Bojangles – 13 years ago

5

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`

skeevey

Posted 13 years ago

Reputation: 4 139

It's a shame C# requires so much typing, you inspired my answer! – Andrew Gray – 13 years ago

5

C#: 106 86 58 46 32 28

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

public int a{get{return a;}}

Andrew Gray

Posted 13 years ago

Reputation: 600

1No need for setter public int a {get{return a;}} – Mike Koder – 13 years ago

3This 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 – 13 years ago

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 – 13 years ago

1The 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 – 13 years ago

1Why "public string"? "int" works just as well: int a { get { return a; } } – NPSF3000 – 12 years ago

Fair point. I was able to remove four characters because of a space before the first curly brace, too! – Andrew Gray – 12 years ago

5

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)

Eric

Posted 13 years ago

Reputation: 191

In Lua, you can just remove all the whitespace. You don't need the spaces between the function and the "end" keyword. – brianush1 – 9 years ago

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 – 13 years ago

Ruby 2.0 - ->x{x[x]}[->y{y[y]}] – John Dvorak – 12 years ago

Mathematica #@#&[#@#&] – alephalpha – 12 years ago

You're just using recursion, then why not do just that, for example in JS: (function x(){x()})() ? – xem – 12 years ago

@xem Requirements say no recursion, that is why. – Danny – 12 years ago

5

INTERCAL, 12 bytes

(1)DO(1)NEXT

Explanation:

NEXT is INTERCAL's version of a subroutine call (or, at least, the closest you can get). It pushes the current position onto the NEXT stack and jumps to the given label.

However, if the NEXT stack length exceeds 80, you get what's pretty much the INTERCAL version of a stack overflow:

ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON
    ON THE WAY TO 1
        CORRECT SOURCE AND RESUBNIT

Try it on Ideone..

kirbyfan64sos

Posted 13 years ago

Reputation: 8 730

6"HAS DISAPPEARED INTO THE BLACK LAGOON" what is this, ArnoldC? – Addison Crump – 10 years ago

5

Mornington Crescent, 139 133

Take Northern Line to Bank
Take Circle Line to Temple
Take Circle Line to Temple
Take Circle Line to Bank
Take Northern Line to Angel

pppery

Posted 13 years ago

Reputation: 3 987

4

Python (17):

c='exec c';exec c

ɐɔıʇǝɥʇuʎs

Posted 13 years ago

Reputation: 4 449

hm, I get KeyError: 'unknown symbol table entry' – stefreak – 8 years ago

4

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

Job

Posted 13 years ago

Reputation: 240

Nice idea: this is a sort of recursion-without-recursion! – Andrea Corbellini – 13 years ago

using a86: dd 0fdeb60 10 characters! – Skizz – 13 years ago

3

Groovy, 5 bytes

run() 

Example execution:

$ groovy -e "run()"
Caught: java.lang.StackOverflowError
java.lang.StackOverflowError
    at script_from_command_line.run(script_from_command_line)
    at script_from_command_line.run(script_from_command_line:1)
    at script_from_command_line.run(script_from_command_line:1)
    ...

works as a command line script (groovy -e), standalone groovy script, and in the groovy shell.

We are not defining a new function here so not breaking the rules as far as I can understand.

This works because the groovy compiler adds an implicit run method behind the scenes and calling this method ourselves causes a StackOverflowException.

Essentially the above run() call gets translated to something like the below code by the groovy compiler before its handed off for execution by the jvm:

// class generated by groovy compiler
class ScriptName { 
  def args 

  def main(args) {
    new ScriptName(args: args).run()
  }

  def run() {
    // user code start
    run() // our call
    // user code end
  }
}

Matias Bjarland

Posted 13 years ago

Reputation: 420

3

Groovy (27 chars)

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

And so it goes:

Caught: java.lang.StackOverflowError
    java.lang.StackOverflowError

Will Lp

Posted 13 years ago

Reputation: 797

3

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

stefreak

Posted 13 years ago

Reputation: 141

Ah just noticed that someone else already exploited the parser in a similar, more elegant way: http://codegolf.stackexchange.com/a/9370/6491

– stefreak – 13 years ago

3

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.

Johannes Kuhn

Posted 13 years ago

Reputation: 7 122

3

J, 3 chars

$:1

This does call itself. But it does not define a function that calls itself. Rather $: keeps invoking the largest verb it is enclosed in.

$:1
|stack error
|       $:1

barbermot

Posted 13 years ago

Reputation: 111

3

Javascript, ES6 21

eval('{'.repeat(1e7))

Due to the nature of javascript, nesting a bunch of blocks causes a stackoverflow.

For more information see https://stackoverflow.com/questions/17306367/why-does-nesting-a-bunch-of-blocks-causes-a-stack-overflow-in-javascript

eval('('.repeat(1e7))

eval('['.repeat(1e7))

Other similar cases

eval('+'.repeat(1e7))

eval('-'.repeat(1e7))

Afonso Matos

Posted 13 years ago

Reputation: 312

3

Vitsy, 1 byte

Obviously non-competing due to language creation date.

This feature of my language was entirely unintended. Because of how loops work in my language, they can be finicky if you don't match braces. So, for a one-byte solution, I give you this:

[

Posted on my Showcase your language one vote at a time! answer...

The shortest stack overflow error you'll ever see.

Basically, in Vitsy, the [ represents "start while loop". While in a while loop, the program will wrap around the line - which means it starts another while loop, which wraps around the line and starts another while...

You get it.

Try it online!

Addison Crump

Posted 13 years ago

Reputation: 10 763

3

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!?!.

dmckee --- ex-moderator kitten

Posted 13 years ago

Reputation: 2 726

O(){o(o());} saves a character. Replacing O with recursive main call saves more. – ugoren – 13 years ago

‘You are not allowed to define a function that calls itself.’ I think we both agree that using an intermediary doesn't excuse it, so why post it as a ‘solution’? – Anonymous – 8 years ago

Because poking your nose through loopholes in the question description is a prestigious line of work with a long and glorious tradition on [codegolf.se]? – dmckee --- ex-moderator kitten – 8 years ago

3

Brachylog, 4 bytes (Non-competing)

$G~l

Try it online!

Explanation

$G is 1,000,000,000. $G~l is thus: “Create a list of length 1,000,000,000”, which does not fit the stack.

Fatalize

Posted 13 years ago

Reputation: 32 976

2

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.

AutomatedChaos

Posted 13 years ago

Reputation: 291

2

Scheme:

((lambda (x) (x x)) (lambda (x) (x x))

pjc

Posted 13 years ago

Reputation: 21

Citing the question: "you are not allowed to define function that calls itself" – Tomas – 12 years ago

1These functions aren't written to call themselves. Instead, (lambda (x) (x x) is a function with one parameter that x, that calls x as a function, passing x as a argument. – kernigh – 11 years ago

1In Racket: ((λ (x) (x x)) (λ (x) (x x))) – Roberto Bonvallet – 11 years ago

2

Burlesque, 5 characters

1R@p^

Range from one to infinity, push all elements to stack -> StackOverflow.

mroman

Posted 13 years ago

Reputation: 1 382

2

PERL, 19 chars

sub c{sub d{c()}d}c

Originally I posted this solution (11 chars), but I overlook that rule "You are not allowed to define a function that calls itself":

sub c{c()}c

It's a pitty that PERL doesn't allow this sub c{c}c - would look really cute :-)

Tomas

Posted 13 years ago

Reputation: 2 333

You can get down to 18 characters with sub c{sub d{&c}d}c. I also tried sub c{&{$_[0]}}c\&c, but that one is also 19 characters. – kernigh – 11 years ago

2

LI, 1 byte (non-competing)

R

Reruns the program with the given input. Every time this is done, another two functions are added to the interpreter's stack (one interpreting the program string and another interpreting the function R), eventually overflowing the stack.

Steven H.

Posted 13 years ago

Reputation: 2 841

1

Lua

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

Alternatively,

a={}setmetatable(a,{__index=function()return a.a end})a(a.a) --C stack overflow

mniip

Posted 13 years ago

Reputation: 9 396

"You are not allowed to define a function that calls itself". That aside, what language is this? – Peter Taylor – 13 years ago

@PeterTaylor: These are two separate Lua programs.

– PleaseStand – 13 years ago

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 – 13 years ago

1

SmileBASIC, 63 bytes

PRGEDIT 1FOR I=0TO 16384PRGSET"GOSUB"+(@_+HEX$(I))*2NEXT
EXEC 1

Error: Stack overflow in 1:16385

This generates code like:

GOSUB @_0@_0
GOSUB @_1@_1
...

No recursion is used, just 16385 GOSUBs, enough to fill the call stack.

And a boring and possibly cheating answer in 10 bytes:

@A
GOSUB@A

Error: Stack overflow in 0:2

12Me21

Posted 13 years ago

Reputation: 6 110

‘You are not allowed to define a function that calls itself.’ – Anonymous – 8 years ago

It's not a function though. Functions in SB are created using DEF, for example: a:DEF a:a:END would trigger a stack overflow. – 12Me21 – 8 years ago

Semantics. Gosub is used to call a subprogram, and it overflows because you're pushing the same return point on the stack. So this overflows the stack for the same reason, in the same manner, as calling a recursive function in some other programming language. This solution is against the rules. – Anonymous – 8 years ago

At that point you might as well ban anything that involves any type of stack, then, which would make this impossible. – 12Me21 – 8 years ago

How does that follow? Just read the rules. Recursively calling the same function is prohibited, but e.g. calling loads of different non-recursive functions isn't. How is that so hard to understand? – Anonymous – 8 years ago

And, as an afterthought, not only is the rule and the spirit behind it easy to understand, but the reason the rule is there is pretty obvious too: anyone can overflow the stack with a recursive function. There's no trick to it and programs overflowing the stack through a recursive function call are utterly uninteresting. Just look at your own submission. – Anonymous – 8 years ago

Look at “dofile’a’” in Lua. It’s just a program which recursively calls itself, just like you would define a function that calls itself. The only difference is the name (just like mine). – 12Me21 – 8 years ago

1

Whitespace, 12 bytes - Fills the stack


  
   

 


Try it online!

Explanation

nssn ; Declare label ''
sssn ; Push 0
nsnn ; Jump to label ''

Cloned from Shortest program that continually allocates memory. Whitespace is actually somewhat competitive for this question, I'm surprised we hadn't already had an answer.

This program loops and continuously pushes the value 0 to the stack, causing the stack to grow until the interpreter crashes (with the equivalent of a stack overflow error in whatever language the interpreter uses).

Ephphatha

Posted 13 years ago

Reputation: 581

1

Braingolf, 5 bytes

1[l>]

Pushes a 1, then repeatedly pushes the length of the stack and moves it to the beginning of the stack. The loop will only exit if the first item in the stack is 0, so this loop will continually increase the length of the stack until eventually it reaches python3's deque limit.

Skidsdev

Posted 13 years ago

Reputation: 9 656

1

GW-Basic, 18 bytes

In GW-Basic there's no separate stack overflow error as such; when the stack overflows you get error 7, ‘Out of memory’. The trick is to make sure you got this because you've ran out of stack space and not for some other reason. Enter:

CLEAR,,241:?SIN(0)

This will immediately result in:

Out of memory
Ok

The number 241 is important. Firstly, it cannot be 0 because that will yield error 5 ‘Illegal function call’. But it also cannot be 240 or less, because although you will get the out of memory error above, CLEAR won't actually have adjusted the stack space. So in that case the error isn't a real stack overflow, but it acts more like an illegal argument error of sorts. ‘This is too small for us to work with at all, no can do, sorry.’ You can easily check this:

CLEAR,,999
Ok 
CLEAR,,1
Out of memory
Ok 
?SIN(0)
 0
Ok 
CLEAR,,240
Out of memory
Ok 
?SIN(0)
 0
Ok 
CLEAR,,241
Ok 
?SIN(0)
Out of memory

Anonymous

Posted 13 years ago

Reputation: 161

1

dc, 7 chars

[ddx]dx

You may watch how it consumes memory :-)

dc -e'[ddx]dx' & watch -n 1 "ps l|grep $!|grep -v grep"

Tomas

Posted 13 years ago

Reputation: 2 333

When run in OpenBSD dc(1), this program overflows the data stack, not the call stack. The question never said which stack to overflow! Running dc -e '[dx ]dx overflows the call stack, because OpenBSD won't optimize tail recursion if there is space in x ]. – kernigh – 11 years ago

1@kernigh what is "data stack"? There is only one stack present, and this is a call stack. – Tomas – 11 years ago

1

Java + SnakeYaml and a quirk over jva.awt.point :P; length=104

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

masterX244

Posted 13 years ago

Reputation: 3 942

1

C#

(59)

With a Main method:

static void Main(){unsafe{int* p=stackalloc int[1000000];}}

(39)

Just the code that causes the exception:

unsafe{int* p=stackalloc int[1000000];}

Abbas

Posted 13 years ago

Reputation: 349

1

x86_64 ASM - 7 bytes

48 81 EC 00 00 60 09

Here is a mnemonic version.

SUB RSP, 0x9600000

This instruction by setting the stack pointer to above the maximum size, (at least on Unix) Since the stack grows downwards we use subtraction instead of addition.

You could probably also exchange RSP with RBP top set the base pointer of stack to overflow. This would require you to change EC to ED in the hex representation.

Although this doesn't throw an error, the stack is overflowed as we set the size that the stack is filled to a number above the maximum stack size.

You could improve this answer to 4 bytes if you are using an operating system with a stack size to less than one byte.

48 81 EC FF

gyroninja

Posted 13 years ago

Reputation: 11

1

TECO, 4 bytes

I was thinking about what tasks would be best to do in TECO, and realized that infinite loops and stack overflows are among its greatest talents.

<[a>

Pushes the contents of register a to the stack in an infinite loop.

Result of running code:

*<[a>$$
?PDO   Push-down list overflow

feersum

Posted 13 years ago

Reputation: 29 566

1

Neoscript, 22 bytes

try 1/0;catch e retry;

The division by 0 crash and execute the catch block, which call the try..catch block again, the division by 0 crash and excute the catch block again, etc...

TuxCrafting

Posted 13 years ago

Reputation: 4 547

0

Rust, 29 bytes

fn main(){let a=[0;9000000];}

I hadn't thought it would be that easy. It actually gives segmentation fault, but given that it's rust, I'm pretty sure it's the stack that throws in the towel.

I wonder if the compiler ought to give a warning about stuff like this?

Harald Korneliussen

Posted 13 years ago

Reputation: 430

0

C#: 62 (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(){a=a;}}

It'sNotALie.

Posted 13 years ago

Reputation: 209

I think someone else already posted that. – Johannes Kuhn – 12 years ago

0

R - 5 (plus 18 for the command line switch)

Using a ridiculously small memory allocation (--max-mem-size=32M), you can do this easily:

1:1e9

I tried this without setting the memory limit, and that caused my computer to hang. I don't know if it would have overflowed or not. If not, a score of 6 (1:1e99) would surely do it.

Gaffi

Posted 13 years ago

Reputation: 3 411

1Exhausted memory is not a stack overflow. – Tomas – 12 years ago

0

fish shell (14 characters)

In my opinion, this doesn't count as declaring a function that calls itself. Could be shorter if this pull request would be applied (by one character), but considering it wasn't yet (and I'm not going to do this just to make my code shorter), this has to work.

alias ls ll;ls

Konrad Borowski

Posted 13 years ago

Reputation: 11 185

0

In Java : 131 characters

public class HelloWorld{public HelloWorld(){main(new String[]{"3","4"});}public static void main(String []args){new HelloWorld();}}

user12473

Posted 13 years ago

Reputation: 1

Violates the you may not define a function that calls itself rule. main() transitively calls itself – pppery – 9 years ago

1The question is a code-golf question, so remove all unnecessary whitespace, 'golf' your code and add the character count. – ProgramFOX – 12 years ago

0

Batch (7 chars)

It requires CALL or the execution of the calling batch ends right after starting itself again.

CALL %0

I'm not defining a function which calls itself, hence Batch doesn't even have functions. Also I did not create any classes. So this is valid.

Ray

Posted 13 years ago

Reputation: 109

0

Node.js REPL (15)

eval(RegExp.$1)

Sample session:

> eval(RegExp.$1)
RangeError: Maximum call stack size exceeded
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)

nyuszika7h

Posted 13 years ago

Reputation: 1 624

0

C, 24 characters (no cheating)

x(){main();}main(){x();}

Compile with default cc settings and ignore warnings.

C, 10 characters (with cheat)

X{Y;}Y{X;}

compile with:

cc -DX='x()' -DY='main()'

Todd Lehman

Posted 13 years ago

Reputation: 1 723

Violates the you may not define a function that calls itself rule. main() transitively calls itself. – FUZxxl – 11 years ago

0

CoffeeScript/Javascript - Only in Chrome (24 chars)

Sorry for waking up an old post

This only works in Google Chrome (tested in Firefox and Chrome):

JSON.stringify a:5,->a:5

http://coffeescript.org/#try:JSON.stringify%20a%3A5%2C-%3Ea%3A5

This is not converting a circular structure to JSON. Actually, it uses the replacer function: the replacer function returns another object so the object ends up stringifying that object whose replacer also returns an object.

It gets compiled to the following JavaScript:

JSON.stringify({
  a: 5
}, function() {
  return {
    a: 5
  };
});

Tested on Chrome 39.

soktinpk

Posted 13 years ago

Reputation: 4 080

0

Lua, 29 bytes

This one causes a stack overflow by generating a new function every call and calling it.

l=loadstring s='l(s)()'l(s)()

Here are some other creative answers:

9 bytes:

dofile'a'

This causes a C-stack overflow. Requires you put it in a file named a.

39 bytes:

package.loaded.a=z require'a'

This causes a C-stack overflow. Requires to be put in a file named a and requires LUA_PATH=a.

thenumbernine

Posted 13 years ago

Reputation: 341

0

Ruby - Proc fun - 18

a=->(b){b[b]};a[a]

Basic recursive solution. In irb ends up with:

SystemStackError: stack level too deep

Biketire

Posted 13 years ago

Reputation: 200

0

ANTLR4 / Java, 103 Bytes

grammar P;
r:(C|N)+;
C:(('p'|'i')P);
P:(N|S)*;
N:[0-9]+;
S:[A-Za-z0-9_]*;
WS:[ \r\n]+ -> skip;

To use: Better create a new directory to put the file in, I used the common aliases shown on the antlr4 site.

antlr4 P.g4 && javac P*.java && echo 'Press Ctrl-D in 5 secs.' && grun P r -gui

Don't have any idea why this works, and I think it can be golfed much.

Mega Man

Posted 13 years ago

Reputation: 1 379

-1

Java (OpenJDK 9), 70 bytes

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

Try it online!

Serverfrog

Posted 13 years ago

Reputation: 245

You are not allowed to define a function that calls itself. The exception for main was meant for creating a new class, not for recursion. – fəˈnɛtɪk – 9 years ago

That is quite the same as the Groovy Solution. – Serverfrog – 9 years ago

Also, is it even necessary to pass main args? – fəˈnɛtɪk – 9 years ago

I do, I pass args, the String[] which the main method receives. could name it shorter as I see it – Serverfrog – 9 years ago