75
\$\begingroup\$

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.

\$\endgroup\$

closed as unclear what you're asking by caird coinheringaahing, Xcali, 0 ', Sriotchilism O'Zaic, Laikoni Nov 1 '17 at 9:03

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 4
    \$\begingroup\$ I don't understand "use the classes of the selected programming language" \$\endgroup\$ – Prince John Wesley Jan 4 '13 at 15:07
  • 3
    \$\begingroup\$ Is it ok to define a function that calls inner function like this def s{def t=s;t} ? \$\endgroup\$ – Prince John Wesley Jan 4 '13 at 15:10
  • 12
    \$\begingroup\$ 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. \$\endgroup\$ – ceased to turn counterclockwis Jan 4 '13 at 21:42
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – dmckee Jan 4 '13 at 22:13
  • 1
    \$\begingroup\$ 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/… \$\endgroup\$ – jsedano Apr 9 '13 at 16:24

68 Answers 68

3
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ O(){o(o());} saves a character. Replacing O with recursive main call saves more. \$\endgroup\$ – ugoren Jan 15 '13 at 7:43
  • \$\begingroup\$ ‘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’? \$\endgroup\$ – Anonymous Jul 23 '17 at 21:52
  • \$\begingroup\$ Because poking your nose through loopholes in the question description is a prestigious line of work with a long and glorious tradition on Code Golf? \$\endgroup\$ – dmckee Jul 23 '17 at 22:17
3
\$\begingroup\$

Groovy (27 chars)

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

And so it goes:

Caught: java.lang.StackOverflowError
    java.lang.StackOverflowError
\$\endgroup\$
3
\$\begingroup\$

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

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

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.

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

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

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

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!

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

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.

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

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
  }
}
\$\endgroup\$
2
\$\begingroup\$

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.

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

Scheme:

((lambda (x) (x x)) (lambda (x) (x x))
\$\endgroup\$
  • \$\begingroup\$ Citing the question: "you are not allowed to define function that calls itself" \$\endgroup\$ – Tomas Feb 2 '14 at 15:59
  • 1
    \$\begingroup\$ These 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. \$\endgroup\$ – kernigh May 15 '14 at 22:03
  • 1
    \$\begingroup\$ In Racket: ((λ (x) (x x)) (λ (x) (x x))) \$\endgroup\$ – Roberto Bonvallet Jun 9 '14 at 15:10
2
\$\begingroup\$

Burlesque, 5 characters

1R@p^

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

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

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – kernigh May 15 '14 at 21:45
2
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Lua

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

Alternatively,

a={}setmetatable(a,{__index=function()return a.a end})a(a.a) --C stack overflow
\$\endgroup\$
  • \$\begingroup\$ "You are not allowed to define a function that calls itself". That aside, what language is this? \$\endgroup\$ – Peter Taylor Jan 15 '13 at 18:43
  • \$\begingroup\$ @PeterTaylor: These are two separate Lua programs. \$\endgroup\$ – PleaseStand Jan 15 '13 at 19:16
  • \$\begingroup\$ 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. \$\endgroup\$ – RBerteig Apr 17 '13 at 21:44
1
\$\begingroup\$

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"
\$\endgroup\$
  • \$\begingroup\$ 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 ]. \$\endgroup\$ – kernigh May 15 '14 at 21:29
  • 1
    \$\begingroup\$ @kernigh what is "data stack"? There is only one stack present, and this is a call stack. \$\endgroup\$ – Tomas May 26 '14 at 15:05
1
\$\begingroup\$

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());}}
\$\endgroup\$
1
\$\begingroup\$

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];}
\$\endgroup\$
1
\$\begingroup\$

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

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

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

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

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

\$\endgroup\$
  • \$\begingroup\$ ‘You are not allowed to define a function that calls itself.’ \$\endgroup\$ – Anonymous Jul 23 '17 at 21:31
  • \$\begingroup\$ 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. \$\endgroup\$ – 12Me21 Jul 25 '17 at 20:43
  • \$\begingroup\$ 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. \$\endgroup\$ – Anonymous Jul 26 '17 at 12:47
  • \$\begingroup\$ At that point you might as well ban anything that involves any type of stack, then, which would make this impossible. \$\endgroup\$ – 12Me21 Aug 2 '17 at 12:09
  • \$\begingroup\$ 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? \$\endgroup\$ – Anonymous Oct 25 '17 at 18:21
0
\$\begingroup\$

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;}}
\$\endgroup\$
  • \$\begingroup\$ I think someone else already posted that. \$\endgroup\$ – Johannes Kuhn Jun 1 '13 at 19:16
0
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Exhausted memory is not a stack overflow. \$\endgroup\$ – Tomas Feb 2 '14 at 15:59
0
\$\begingroup\$

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

In Java : 131 characters

public class HelloWorld{public HelloWorld(){main(new String[]{"3","4"});}public static void main(String []args){new HelloWorld();}}
\$\endgroup\$
  • 1
    \$\begingroup\$ The question is a code-golf question, so remove all unnecessary whitespace, 'golf' your code and add the character count. \$\endgroup\$ – ProgramFOX Jan 1 '14 at 12:26
  • \$\begingroup\$ Violates the you may not define a function that calls itself rule. main() transitively calls itself \$\endgroup\$ – pppery May 17 '16 at 13:28
0
\$\begingroup\$

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.

\$\endgroup\$

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