# Shortest program that throws StackOverflow Error [closed]

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.

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

## C -- 34 characters, no libraries

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

• O(){o(o());} saves a character. Replacing O with recursive main call saves more. – ugoren Jan 15 '13 at 7:43
• ‘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 Jul 23 '17 at 21:52
• 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? – dmckee --- ex-moderator kitten Jul 23 '17 at 22:17

## Groovy (27 chars)

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


And so it goes:

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


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

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

# 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


# Javascript, ES6 21

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


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

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

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


Other similar cases

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

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


# 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!

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


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

Scheme:

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

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

Burlesque, 5 characters

1R@p^


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

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

• 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 May 15 '14 at 21:45 # 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. # Lua function b()b()end b() --stack overflow  Alternatively, a={}setmetatable(a,{__index=function()return a.a end})a(a.a) --C stack overflow  • "You are not allowed to define a function that calls itself". That aside, what language is this? – Peter Taylor Jan 15 '13 at 18:43 • @PeterTaylor: These are two separate Lua programs. – PleaseStand Jan 15 '13 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 '13 at 21:44 # 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"

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

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


# 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];}


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


# 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


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

# Whitespace, 12 bytes - Fills the stack





Try it online!

## Explanation

nssn ; Declare label ''
sssn ; Push 0


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

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

# 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


# 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

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

# 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;}}

• I think someone else already posted that. – Johannes Kuhn Jun 1 '13 at 19:16

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

• Exhausted memory is not a stack overflow. – Tomas Feb 2 '14 at 15:59

# 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


In Java : 131 characters

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

• The question is a code-golf question, so remove all unnecessary whitespace, 'golf' your code and add the character count. – ProgramFOX Jan 1 '14 at 12:26
• Violates the you may not define a function that calls itself rule. main() transitively calls itself – pppery May 17 '16 at 13:28

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