160

To commemorate the public launch of Stack Overflow, what's the shortest code to cause a stack overflow? Any language welcome.

ETA: Just to be clear on this question, seeing as I'm an occasional Scheme user: tail-call "recursion" is really iteration, and any solution which can be converted to an iterative solution relatively trivially by a decent compiler won't be counted. :-P

ETA2: I've now selected a “best answer”; see this post for rationale. Thanks to everyone who contributed! :-)

Community
  • 1
  • 1
C. K. Young
  • 219,335
  • 46
  • 382
  • 435

129 Answers129

291

Read this line, and do what it says twice.

jrudolph
  • 8,307
  • 4
  • 32
  • 50
211

All these answers and no Befunge? I'd wager a fair amount it's shortest solution of them all:

1

Not kidding. Try it yourself: http://www.quirkster.com/iano/js/befunge.html

EDIT: I guess I need to explain this one. The 1 operand pushes a 1 onto Befunge's internal stack and the lack of anything else puts it in a loop under the rules of the language.

Using the interpreter provided, you will eventually--and I mean eventually--hit a point where the Javascript array that represents the Befunge stack becomes too large for the browser to reallocate. If you had a simple Befunge interpreter with a smaller and bounded stack--as is the case with most of the languages below--this program would cause a more noticeable overflow faster.

Patrick
  • 90,362
  • 11
  • 51
  • 61
  • 8
    Hmm … but is this really a stack overflow or just an infinite loop? My JS interpreter did *not* overflow, it just went on vacation, so to speak. – Konrad Rudolph Sep 16 '08 at 07:53
  • 3
    It's not an infinite loop, because the 1 instruction pushes a 1 onto the stack. Eventually, your Befunge interpreter will run out of stack space, but it'll take a while. :) – Patrick Sep 16 '08 at 09:34
  • 18
    You.. crashed my browser and.. sent my CPU fan into overdrive. – Sam Becker May 11 '09 at 15:01
  • 2
    Amazing! My computer or browser (Opera) didn't crash but both processors were running on 100% and the fan speed was at 3. – Secko Nov 22 '09 at 02:30
  • 28
    Here's a Befunge program that overflows faster: `"` It loads 79 copies of the number 32 every two times it wraps around, rather than 2 copies of the number 1. – KirarinSnow Apr 21 '10 at 01:31
173

You could also try this in C#.net

throw new StackOverflowException();
GateKiller
  • 74,180
  • 73
  • 171
  • 204
  • 29
    The pedant in me says it doesn't cause any stack to overflow, just throws an exception. That's like saying the quickest way to be attacked by sharks is to stand in the sea and scream "Shark attack!". Despite this, I will up-vote it. :) – Bernard Sep 16 '08 at 03:06
  • Well - is there a difference? Can you catch it and continue? Or is it exactly like a stackoverflow in c#? In that case, it somehow is a stackoverflow, since it is indistinguishable from one... However - upvote for all the reasons above – Mo. Sep 16 '08 at 11:52
  • 18
    If a stack overflows in the woods with nobody around to catch, does it throw an exception? –  Apr 13 '10 at 07:53
  • I wouldn't say the 'shortest' since it's not like you can compile a one-liner like that. It _does_ throw a stack overflow quickly though I guess. – Dominic K Sep 22 '10 at 04:54
159

Nemerle:

This crashes the compiler with a StackOverflowException:

def o(){[o()]}
Serafina Brocious
  • 30,433
  • 12
  • 89
  • 114
119

My current best (in x86 assembly) is:

push eax
jmp short $-1

which results in 3 bytes of object code (50 EB FD). For 16-bit code, this is also possible:

call $

which also results in 3 bytes (E8 FD FF).

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 6
    Counting the bytes after "compiling" (or assembling) is not code-golf. – Louis Brandy Sep 15 '08 at 13:38
  • 37
    The question says "[...] what's the shortest code to cause a stack overflow?" It doesn't specify source code, interpreted code, machine code, object code or managed code... – Anders Sandvig Sep 15 '08 at 13:42
  • For the record, Shin's golf server allows you to send object code to be judged, although it will count all your ELF headers too. Hmm.... – C. K. Young Sep 15 '08 at 23:35
  • See, e.g., http://golf.shinh.org/p.rb?FizzBuzz#x86 for some examples of this. (I honestly don't know how people can make 99-byte ELF binaries, though.) :-P – C. K. Young Sep 15 '08 at 23:36
  • 7
    @lbrandy: There are enough people who can write object code directly. I can't do it for x86 but for a certain microprocessor I can. I'd count such code. – Joey Jul 03 '10 at 22:39
113

PIC18

The PIC18 answer given by TK results in the following instructions (binary):

overflow
   PUSH
   0000 0000 0000 0101
   CALL overflow
   1110 1100 0000 0000
   0000 0000 0000 0000

However, CALL alone will perform a stack overflow:

CALL $
1110 1100 0000 0000
0000 0000 0000 0000

Smaller, faster PIC18

But RCALL (relative call) is smaller still (not global memory, so no need for the extra 2 bytes):

RCALL $
1101 1000 0000 0000

So the smallest on the PIC18 is a single instruction, 16 bits (two bytes). This would take 2 instruction cycles per loop. At 4 clock cycles per instruction cycle you've got 8 clock cycles. The PIC18 has a 31 level stack, so after the 32nd loop it will overflow the stack, in 256 clock cycles. At 64MHz, you would overflow the stack in 4 micro seconds and 2 bytes.

PIC16F5x (even smaller and faster)

However, the PIC16F5x series uses 12 bit instructions:

CALL $
1001 0000 0000

Again, two instruction cycles per loop, 4 clocks per instruction so 8 clock cycles per loop.

However, the PIC16F5x has a two level stack, so on the third loop it would overflow, in 24 instructions. At 20MHz, it would overflow in 1.2 micro seconds and 1.5 bytes.

Intel 4004

The Intel 4004 has an 8 bit call subroutine instruction:

CALL $
0101 0000

For the curious that corresponds to an ascii 'P'. With a 3 level stack that takes 24 clock cycles for a total of 32.4 micro seconds and one byte. (Unless you overclock your 4004 - come on, you know you want to.)

Which is as small as the befunge answer, but much, much faster than the befunge code running in current interpreters.

Community
  • 1
  • 1
Adam Davis
  • 91,931
  • 60
  • 264
  • 330
77

C#:

public int Foo { get { return Foo; } }
TJ L
  • 23,914
  • 7
  • 59
  • 77
aku
  • 122,288
  • 32
  • 173
  • 203
57

Hoot overflow!

//              v___v
let rec f o = f(o);(o)
//             ['---']
//             -"---"-
Juliet
  • 80,494
  • 45
  • 196
  • 228
55

Every task needs the right tool. Meet the SO Overflow language, optimized to produce stack overflows:

so
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 7
    If you're making a specialized language for generating overflows with a minimal of code, obviously you would want (1) empty input produces stack overflowing code (probably a small binary that runs the native code generated from the assembly code entry) or (2) all input programs produce said binary. – Jared Updike Sep 18 '08 at 19:08
  • Hmmm, not Turing complete. I don't know if you could call it a language just yet... – Adam Davis Feb 28 '09 at 01:26
42

TeX:

\def~{~.}~

Results in:

! TeX capacity exceeded, sorry [input stack size=5000].
~->~
    .
~->~
    .
~->~
    .
~->~
    .
~->~
    .
~->~
    .
...
<*> \def~{~.}~

LaTeX:

\end\end

Results in:

! TeX capacity exceeded, sorry [input stack size=5000].
\end #1->\csname end#1
                      \endcsname \@checkend {#1}\expandafter \endgroup \if@e...
<*> \end\end
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Alex M
  • 2,458
  • 20
  • 15
  • Since `~` is active, it can be used in place of `\a`. And I discovered the LaTeX code completely by accident. :) – Josh Lee Mar 24 '11 at 15:02
35

Z-80 assembler -- at memory location 0x0000:

rst 00

one byte -- 0xC7 -- endless loop of pushing the current PC to the stack and jumping to address 0x0000.

Dennis Munsie
  • 1,211
  • 12
  • 24
  • 2
    I remember a blank eprom would be all 0xffs which are rst 7 (= call 0x0038) instructions. That would be useful for debugging your hardware with an oscilloscope. The address bus would cycle through the 64K space as the stack overflowed repeatedly, interspersed with reads of 0xff from 0x0038. – Bill Forster Feb 27 '09 at 21:22
29

In english:

recursion = n. See recursion.
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
29

Another PHP Example:

<?
require(__FILE__);
TJ L
  • 23,914
  • 7
  • 59
  • 77
Kemal
  • 2,602
  • 1
  • 21
  • 14
  • 4
    You could even be shorted by skipping the parenthesis (but including space in place of the first). – alex Sep 27 '10 at 05:14
26

How about the following in BASIC:

10 GOSUB 10

(I don't have a BASIC interpreter I'm afraid so that's a guess).

stusmith
  • 14,003
  • 7
  • 56
  • 89
  • 3
    Not really a stack overflow since BASIC is a stackless language. Even VB (which does have a stack) wouldn't overflow on this since it's just jumping, not creating a stack frame. – Daniel Spiewak Sep 16 '08 at 01:16
  • 21
    That's a `GOSUB`, not a `GOTO`. Since it `RETURN`s to where it was called from, surely it's using a stack? – Tom Sep 16 '08 at 01:55
  • 3
    Yeah, I agree. I had *many* stack overflows in BASIC in the 80s. – nickd Sep 16 '08 at 11:14
  • 6
    I ran this one in yabasic just for the fun of it, and it nearly took down my computer. Thank god malloc eventually failed, but I was paging like no tomorrow. – Adam Rosenfield Oct 23 '08 at 05:08
  • 2
    Oops sorry Adam... reminds me of a time at uni when someone accidentally wrote a program that recursively forked: took down an entire Silicon Graphics server. – stusmith Nov 07 '08 at 15:34
  • Just tested it on my VZ200 emulator ?OUT OF MEMORY ERROR IN 10 – johnc Dec 04 '08 at 02:05
  • 1
    WTF is anyone doing with a VZ200 emulator? :-) I don't pine for my old ZX80 or COMX-35. – paxdiablo Jan 20 '11 at 04:04
26

I loved Cody's answer heaps, so here is my similar contribution, in C++:

template <int i>
class Overflow {
    typedef typename Overflow<i + 1>::type type;
};

typedef Overflow<0>::type Kaboom;

Not a code golf entry by any means, but still, anything for a meta stack overflow! :-P

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
21

Here's my C contribution, weighing in at 18 characters:

void o(){o();o();}

This is a lot harder to tail-call optimise! :-P

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 4
    Doesn't compile for me: "undefined reference to `main'" :P – Andrew Johnson Sep 15 '08 at 12:58
  • 1
    I don't understand: why call o() 2x? – Dinah Jun 22 '09 at 19:14
  • 3
    @Dinah: One of the constraints of my contest was that tail-call optimisation doesn't count as recursion; it's just an iterative loop. If you only wrote o() once, that can be tail-call optimised into something like this (by a competent compiler): "o: jmp o". With 2 calls of o, the compiler has to use something like: "o: call o; jmp o". It's the recursive "call" instruction that makes the stack overflow. – C. K. Young Jun 22 '09 at 19:30
  • You're correct -- I didn't pay attention to that part. Thank you for the clarification. – Dinah Jun 23 '09 at 14:46
19

Using a Window's batch file named "s.bat":

call s
Jude Allred
  • 10,977
  • 7
  • 28
  • 27
17

Javascript

To trim a few more characters, and to get ourselves kicked out of more software shops, let's go with:

eval(i='eval(i)');
cgp
  • 41,026
  • 12
  • 101
  • 131
Travis Wilson
  • 949
  • 9
  • 19
15

Please tell me what the acronym "GNU" stands for.

Greg
  • 16,540
  • 9
  • 51
  • 97
15

Groovy:

main()

$ groovy stack.groovy:

Caught: java.lang.StackOverflowError
    at stack.main(stack.groovy)
    at stack.run(stack.groovy:1)
 ...
Chris Broadfoot
  • 5,082
  • 1
  • 29
  • 37
  • Voted up because it's pretty interesting. Exposes a rather annoying weakness in the Groovy compiler though (such tail-calls can be inlined at compile-time). – Daniel Spiewak Sep 16 '08 at 01:20
  • are you sure it's a tail call? that falling off the end of the program doesn't invoke the interpreter shell? – Aaron Sep 18 '08 at 09:53
14
Person JeffAtwood;
Person JoelSpolsky;
JeffAtwood.TalkTo(JoelSpolsky);

Here's hoping for no tail recursion!

Ryan Fox
  • 10,103
  • 5
  • 38
  • 48
  • 1
    Hehe, funny. Related to conversations, the idea of the "echo chamber effect" is quite interesting, too. Not quite stack overflow-inducing, but still. – C. K. Young Sep 17 '08 at 00:13
  • 8
    Wouldn't this be a null pointer exception? Sorry, I know it's a joke. – jamesh Oct 23 '08 at 12:11
12

C - It's not the shortest, but it's recursion-free. It's also not portable: it crashes on Solaris, but some alloca() implementations might return an error here (or call malloc()). The call to printf() is necessary.

#include <stdio.h>
#include <alloca.h>
#include <sys/resource.h>
int main(int argc, char *argv[]) {
    struct rlimit rl = {0};
    getrlimit(RLIMIT_STACK, &rl);
    (void) alloca(rl.rlim_cur);
    printf("Goodbye, world\n");
    return 0;
}
bk1e
  • 23,871
  • 6
  • 54
  • 65
  • You can also just do "ulimit -s16" to set the stack really small. Any smaller than about 16 and the program doesn't even run (insufficient args apparently!). – Andrew Johnson Sep 15 '08 at 16:26
11

Python:

so=lambda:so();so()

Alternatively:

def so():so()
so()

And if Python optimized tail calls...:

o=lambda:map(o,o());o()
cdleary
  • 69,512
  • 53
  • 163
  • 191
Serafina Brocious
  • 30,433
  • 12
  • 89
  • 114
  • Lucky for you, Python doesn't do tail-call optimisation; otherwise, it'd be disqualified like two other answers so far. :-P – C. K. Young Sep 15 '08 at 11:38
11

perl in 12 chars:

$_=sub{&$_};&$_

bash in 10 chars (the space in the function is important):

i(){ i;};i
asksol
  • 19,129
  • 5
  • 61
  • 68
11

try and put more than 4 patties on a single burger. stack overflow.

user8456
  • 346
  • 1
  • 4
  • 12
  • 1
    Here in New Zealand we have Burger Wisconsin, where they use big but thin patties. I'm sure you can stack more than 4 of those if you want to; it'll be a very expensive burger though! – C. K. Young Sep 15 '08 at 23:09
  • Maybe: http://www.alafista.com/2010/05/10/lotteria-tower-cheese-burger-with-10-patties/ Maybe not: http://cheaplightning.blogspot.com/2010/06/lotteria-10-patty-burger-bloody-history.html – BCS Jul 13 '10 at 20:43
  • Mmm... In-n-Out. http://en.wikipedia.org/wiki/In-n-out#Menu – cbednarski Aug 24 '10 at 21:37
10

I'm selecting the “best answer” after this post. But first, I'd like to acknowledge some very original contributions:

  1. aku's ones. Each one explores a new and original way of causing stack overflow. The idea of doing f(x) ⇒ f(f(x)) is one I'll explore in my next entry, below. :-)
  2. Cody's one that gave the Nemerle compiler a stack overflow.
  3. And (a bit grudgingly), GateKiller's one about throwing a stack overflow exception. :-P

Much as I love the above, the challenge is about doing code golf, and to be fair to respondents, I have to award “best answer” to the shortest code, which is the Befunge entry; I don't believe anybody will be able to beat that (although Konrad has certainly tried), so congrats Patrick!

Seeing the large number of stack-overflow-by-recursion solutions, I'm surprised that nobody has (as of current writing) brought up the Y combinator (see Dick Gabriel's essay, The Why of Y, for a primer). I have a recursive solution that uses the Y combinator, as well as aku's f(f(x)) approach. :-)

((Y (lambda (f) (lambda (x) (f (f x))))) #f)
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
8

Here's another interesting one from Scheme:

((lambda (x) (x x)) (lambda (x) (x x)))
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • Very nice, and there's a good symmetry to it too. Also, to use the (lambda (x) (x x)) formulation: ((Y (lambda (x) (x x))) #f) is a lot of fun too! – C. K. Young Sep 16 '08 at 23:37
  • Oh, that's pretty. It works in Ruby, too, although not as pretty as in Scheme: lambda { |x| x.call x }.call lambda { |x| x.call x } – Wayne Conrad Jan 13 '10 at 17:42
7

Java

Slightly shorter version of the Java solution.

class X{public static void main(String[]a){main(a);}}
Misha
  • 1,952
  • 14
  • 10
6
xor esp, esp
ret
5

3 bytes:

label:
  pusha
  jmp label

Update

According to the (old?) Intel(?) documentation, this is also 3 bytes:

label:
  call label

Anders Sandvig
  • 20,720
  • 16
  • 59
  • 73
  • It's 3 bytes in 32-bit mode. Nice answer, considering it'll fill the stack much faster than my answer! – C. K. Young Sep 15 '08 at 13:24
  • According to http://www.penguin.cz/~literakl/intel/j.html#JMP, jmp is 3 bytes with 8, 16 or 32 bit relative destination address. The pusha is also 1 bytes, which makes a total of 4 – Anders Sandvig Sep 15 '08 at 13:32
  • There are three types of jmp, short, near, and far. Short jmp (using 0xEB opcode) is two bytes. Destination must be between -128 and 127 bytes away from the next instruction. :-) – C. K. Young Sep 15 '08 at 13:32
  • Maybe you're right. I'm too lazy to dig out my assembler and verify... ;) – Anders Sandvig Sep 15 '08 at 13:34
4

Java (embarassing):

public class SO 
{ 
  private void killme()
  {
    killme();
  }

  public static void main(String[] args) 
  { 
    new SO().killme(); 
  } 
}

EDIT Of course it can be considerably shortened:

class SO
{
  public static void main(String[] a)
  {
    main(null);
  }
}
Manrico Corazzi
  • 11,299
  • 10
  • 48
  • 62
4

In Lua:

function f()return 1+f()end f()

You've got to do something to the result of the recursive call, or else tail call optimization will allow it to loop forever. Weak for code golf, but nice to have!

I guess that and the lengthy keywords mean Lua won't be winning the code golf anytime soon.

  • Ah. You beat my (unpublished) score. I used f()*f() to avoid the tail call. – Jon 'links in bio' Ericson Sep 15 '08 at 23:17
  • The f()*f() isn't a bad idea, however: apparently (this isn't about Lua anymore BTW) GCC can tail-call optimise 1+f() too, on the premise that f() isn't expected to return, or something. See the comments on #62221 for more details. :-P – C. K. Young Sep 15 '08 at 23:42
4

Forth:

: a 1 recurse ; a

Inside the gforth interpreter:

: a 1 recurse ; a 
*the terminal*:1: Return stack overflow
: a 1 recurse ; a
                ^
Backtrace:

On a Power Mac G4 at the Open Firmware prompt, this just hangs the machine. :)

Alex M
  • 2,458
  • 20
  • 15
4

as a local variable in a C function:

int x[100000000000];
Helen
  • 87,344
  • 17
  • 243
  • 314
4

http://www.google.com/search?q=google.com

Ramin
  • 13,343
  • 3
  • 33
  • 35
3

Ruby:

def s() s() end; s()
dr_bonzo
  • 213
  • 1
  • 2
  • 7
3

GWBASIC output...

OK
10 i=0
20 print i;
30 i=i+1
40 gosub 20
run
 0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21
 22  23  24  25  26  27  28  29  30  31  32  33
Out of memory in 30
Ok

Not much stack depth there :-)

Tim Ring
  • 1,845
  • 1
  • 20
  • 27
3

batch program called call.cmd;

call call.cmd

******  B A T C H   R E C U R S I O N  exceeds STACK limits ******
Recursion Count=1240, Stack Usage=90 percent
******       B A T C H   PROCESSING IS   A B O R T E D      ******
tomdemuyt
  • 4,572
  • 2
  • 31
  • 60
3

In Scheme, this will cause the interpreter to run out of memory:

(define (x)
  ((x)))

(x)
Kyle Cronin
  • 77,653
  • 43
  • 148
  • 164
3

Ruby, shorter than the other ones so far:

def a;a;end;a

(13 chars)

3

C#

class _{static void Main(){Main();}}

Note that mine is a compilable program, not just a single function. I also removed excess whitespace.

For flair, I made the class name as small as I could.

Jay Bazuzi
  • 45,157
  • 15
  • 111
  • 168
  • You could even rename Main if you were willing to require a special command-line option to the compiler. – Joe White Jul 13 '10 at 01:14
3

If you consider a call frame to be a process, and the stack to be your Unix machine, you could consider a fork bomb to be a parallel program to create a stack overflow condition. Try this 13-character bash number. No saving to a file is necessary.

:(){ :|:& };:
user4010
  • 189
  • 3
3

In Irssi (terminal based IRC client, not "really" a programming language), $L means the current command line. So you can cause a stack overflow ("hit maximum recursion limit") with:

/eval $L
Wouter Coekaerts
  • 9,395
  • 3
  • 31
  • 35
2

C#

class Program
{
    class StackOverflowExceptionOverflow : System.Exception
    {
        public StackOverflowExceptionOverflow()
        {
            throw new StackOverflowExceptionOverflow();
        }
    }

    static void Main(string[] args)
    {
        throw new StackOverflowExceptionOverflow();
    }
}

I realize this is not the shortest (and even code golfed it would not come close to be anywhere near short), but I simply could not resist throwing an exception that while being thrown throws a stackoverflowexception, before it is able to terminate the runtime itself ^^

danielschemmel
  • 10,885
  • 1
  • 36
  • 58
2

PostScript, 7 characters

{/}loop

When run in GhostScript, throws this exception:

GS>{/}loop
Error: /stackoverflow in --execute--
Operand stack:
   --nostringval--
Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   %loop_continue   1753   2   3   %oparray_pop   --nostringval--   --nostringval--   false   1   %stopped_push   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   %loop_continue
Dictionary stack:
   --dict:1150/1684(ro)(G)--   --dict:0/20(G)--   --dict:70/200(L)--
Current allocation mode is local
Last OS error: 11
Current file position is 8

Here's the recursive version without using variables (51 chars):

[{/[aload 8 1 roll]cvx exec}aload 8 1 roll]cvx exec
KirarinSnow
  • 1,062
  • 2
  • 9
  • 22
2

Java:

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

Actually causes a stack overflow initializing the X class. Before main() is called, the JVM must load the class, and when it does so it triggers any anonymous static code blocks:

static {
  new X();
}

Which as you can see, instantiates X using the default constructor. The JVM will call anonymous code blocks even before the constructor:

{
  new X();
}

Which is the recursive part.

Draemon
  • 33,955
  • 16
  • 77
  • 104
2

Java: 35 characters

I think it's too late, but I will still post my idea:

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

Using the static initializer and instance initializer features.

Here is the output on my computer (notice it showed two error messages):

Exception in thread "main" java.lang.StackOverflowError
    at A.<init>(A.java:1)
        ......
    at A.<init>(A.java:1)
Could not find the main class: A. Program will exit.

See also: http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/java/javaOO/initial.html

Ming-Tang
  • 17,410
  • 8
  • 38
  • 76
  • Although your answer is still longer than the winning answer :-), it's still a pretty neat approach, so +1 to you! – C. K. Young Aug 26 '10 at 02:21
  • At last, I realized someone else did it first. It's on about the middle pages where it's very hard to find. – Ming-Tang Aug 26 '10 at 05:06
2

C++ Compiler Error Message

template<int n>struct f{f<n+1>a;};f<0>::a;

output:

$ g++ test.cpp;
test.cpp:1: error: template instantiation depth exceeds maximum of 500 (use -ftemplate-depth-NN to increase the maximum) instantiating ‘struct f<500>’
test.cpp:1:   instantiated from ‘f<499>’
test.cpp:1:   instantiated from ‘f<498>’
......

Even if the compiler went through the template, there will be the next error: missing main.

Community
  • 1
  • 1
Ming-Tang
  • 17,410
  • 8
  • 38
  • 76
2

PIC18:

overflow

    PUSH   
    CALL   overflow 
TK.
  • 46,577
  • 46
  • 119
  • 147
2

CIL/MSIL:

loop: ldc.i4.0
br loop

Object code:

16 2B FD
Serafina Brocious
  • 30,433
  • 12
  • 89
  • 114
  • Hmm, will the .NET verifier accept that? For JVM, you have to specify the maximum stack usage, and the verifier will enforce it, so code like the above (iconst_0; goto loop) will get rejected. – C. K. Young Sep 15 '08 at 12:00
2

Lisp

(defun x() (x)) (x)
Ozgur Ozcitak
  • 10,409
  • 8
  • 46
  • 56
  • With some compiler flags, this can also be tail-call optimised. :-) – C. K. Young Sep 15 '08 at 12:35
  • 1
    In current implementations of Common Lisp, you will have to explicitly declaim or declare TCO away. Scheme even requires TCO. To make this surely overflow, don't tail recurse: (defun x () (1+ (x))) (x). – Svante Jun 10 '09 at 06:29
2
a{return a*a;};

Compile with:

gcc -D"a=main()" so.c

Expands to:

main() {
    return main()*main();
}
Andrew Johnson
  • 7,277
  • 4
  • 23
  • 27
2

F#

People keep asking "What is F# useful for?"

let rec f n =
    f (n)

performance optimized version (will fail faster :) )

let rec f n =
    f (f(n))
aku
  • 122,288
  • 32
  • 173
  • 203
2

In Whitespace, I think:

It probably won't show up. :/

Robert S.
  • 25,266
  • 14
  • 84
  • 116
  • 1
    Browsers won't show tabs very well to begin with, and Markdown just completely obliterates it. I'll paste in what I can see (editing privileges for the win!) in my next comment. – C. K. Young Sep 16 '08 at 23:53
  • 4
    SP SP SP TAB NL NL SP SP SP TAB SP SP SP SP TAB TAB NL TAB SP SP SP NL SP TAB SP TAB SP SP SP SP TAB TAB NL NL NL – C. K. Young Sep 16 '08 at 23:55
2

Haskell:

let x = x
print x
mattiast
  • 1,934
  • 12
  • 18
2

Well, nobody's mentioned Coldfusion yet, so...

<cfinclude template="#ListLast(CGI.SCRIPT_NAME, "/\")#">

That oughta do it.

Joshua Carmody
  • 13,410
  • 16
  • 64
  • 83
2

Unless there's a language where the empty program causes a stack overflow, the following should be the shortest possible.

Befunge:

:

Duplicates the top stack value over and over again.

edit: Patrick's is better. Filling the stack with 1s is better than filling the stack with 0s, since the interpreter could optimize pushing 0s onto an empty stack as a no-op.

clahey
  • 4,795
  • 3
  • 27
  • 20
2

Groovy (5B):

run()
matyr
  • 5,774
  • 28
  • 22
1

GNU make:

Create a file called "Makefile" with the following contents:

a:
    make

Then run make:

$ make

Note that a tab character must be used to offset the word "make". This file is 9 characters, including the 2 end-of-line characters and the 1 tab character.

I suppose you could do a similar thing with bash, but it's probably too easy to be interesting:

Create a filename "b" and mark it as executable (chmod +x b):

b ## ties the winning entry with only one character (does not require end-of-line)

Now execute the file with

$ ( PATH=$PATH:. ; b )

It's hard to say whether this approach technically results in stack overflow, but it does build a stack which will grow until the machine runs out of resources. The cool thing about doing it with GNU make is that you can watch it output status information as it builds and destroys the stack (assuming you hit ^C at some point before the crash occurs).

Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
1

PHP is a recursive acronym

Cyclone
  • 17,939
  • 45
  • 124
  • 193
1

CMD overflow in one line

echo @call b.cmd > b.cmd & b
Helen
  • 87,344
  • 17
  • 243
  • 314
1

In Haskell

fix (1+)

This tries to find the fix point of the (1+) function (λ n → n + 1) . The implementation of fix is

fix f = (let x = f(x) in x)

So

fix (1+)

becomes

(1+) ((1+) ((1+) ...))

Note that

fix (+1)

just loops.

Jonas Kölker
  • 7,680
  • 3
  • 44
  • 51
1
/* In C/C++ (second attempt) */

int main(){
    int a = main() + 1;
    return a;
}
Agnel Kurian
  • 57,975
  • 43
  • 146
  • 217
1

c# again:

class Foo { public Foo() {new Foo(); } }
aku
  • 122,288
  • 32
  • 173
  • 203
1

Complete Delphi program.

program Project1;
{$APPTYPE CONSOLE}
uses SysUtils;

begin
  raise EStackOverflow.Create('Stack Overflow');
end.
JosephStyons
  • 57,317
  • 63
  • 160
  • 234
1

so.c in 15 characters:

main(){main();}

Result:

antti@blah:~$ gcc so.c -o so
antti@blah:~$ ./so
Segmentation fault (core dumped)

Edit: Okay, it gives warnings with -Wall and does not cause a stack overflow with -O2. But it works!

Antti Kissaniemi
  • 18,944
  • 13
  • 54
  • 47
  • Blech! That's undefined, because you have an implicit int return, with no actual return value. If you declared main as void (for some reason), then tail call optimisation can apply. So, nope. :-P – C. K. Young Sep 15 '08 at 12:54
1

JavaSript:

Huppies answer to one line:

(function i(){ i(); })()

Same amount of characters, but no new line :)

Leo Lännenmäki
  • 2,720
  • 1
  • 16
  • 13
1

Java (complete content of X.java):

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

Considering all the syntactic sugar, I am wondering if any shorter can be done in Java. Anyone?

EDIT: Oops, I missed there is already almost identical solution posted.

EDIT 2: I would say, that this one is (character wise) the shortest possible

class X{public static void main(String[]a){main(null);}}

EDIT 3: Thanks to Anders for pointing out null is not optimal argument, so it's shorter to do:

class X{public static void main(String[]a){main(a);}}
Michal
  • 1,262
  • 1
  • 12
  • 22
1

There was a perl one already, but this is a couple characters shorter (9 vs 12) - and it doesn't recurse :)

s//*_=0/e

shelfoo
  • 1,569
  • 13
  • 15
  • Nice! That's clever. But it doesn't work in 5.10: $> perl -e's//*_=0/e' perl(30740) malloc: *** error for object 0x301070: double free *** set a breakpoint in malloc_error_break to debug – asksol Sep 15 '08 at 16:57
  • Same error here on my Perl 5.8.8. :-( – C. K. Young Sep 15 '08 at 23:02
1

I have a list of these at Infinite Loop on E2 - see just the ones indicated as "Stack Overflow" in the title.

I think the shortest there is

[dx]dx

in dc. There may be a shorter solution in False.

EDIT: Apparently this doesn't work... At least on GNU dc. Maybe it was on a BSD version.

Jesse Millikan
  • 3,104
  • 1
  • 21
  • 32
1

Shell script solution in 10 characters including newlines:

Well, technically not stack overflow but logically so, if you consider spawning a new process as constructing a new stack frame.

#!sh
./so

Result:

antti@blah:~$ ./so
[disconnected]

Whoops. Note: don't try this at home

Antti Kissaniemi
  • 18,944
  • 13
  • 54
  • 47
1

PowerShell

$f={&$f};&$f

"The script failed due to call depth overflow. The call depth reached 1001 and the maximum is 1000."

x0n
  • 51,312
  • 7
  • 89
  • 111
1

In assembly language (x86 processors, 16 or 32 bit mode):


call $

which will generate:

  • in 32 bit mode: 0xe8;0xfb;0xff;0xff;0xff

  • in 16 bit mode: 0xe8;0xfd;0xff

in C/C++:


int main( ) {
  return main( );
}
botismarius
  • 2,977
  • 2
  • 30
  • 29
1

TCL:

proc a {} a

I don't have a tclsh interpreter that can do tail recursion, but this might fool such a thing:

proc a {} "a;a"
Joseph Bui
  • 1,701
  • 15
  • 22
1

won't be the shortest but I had to try something... C#

string[] f = new string[0]; Main(f);

bit shorter

static void Main(){Main();}
user10178
  • 532
  • 1
  • 4
  • 13
1

Here's another Ruby answer, this one uses lambdas:

(a=lambda{a.call}).call
RFelix
  • 11
  • 4
1

Another one in JavaScript:

(function() { arguments.callee() })()
Leo Lännenmäki
  • 2,720
  • 1
  • 16
  • 13
1

Vb6


Public Property Let x(ByVal y As Long)
  x = y
End Property

Private Sub Class_Initialize()
  x = 0
End Sub
Javier
  • 103
  • 1
  • 6
  • Nice. Similar theme to one of aku's solutions (except there it was a property getter, and here it's a property setter). +1! – C. K. Young Sep 16 '08 at 23:14
1

Short solution in K&R C, could be compiled:

main(){main()}

14 bytes

squadette
  • 8,177
  • 4
  • 28
  • 39
1

In response to the Y combinator comment, i might as well through in the Y-combinator in the SKI calculus:

S (K (S I I)) (S (S (K S) K) (K (S I I)))

There aren't any SKI interpreters that i know of but i once wrote a graphical one in about an hour in actionscript. I would be willing to post if there is interest (though i never got the layout working very efficiently)

read all about it here: http://en.wikipedia.org/wiki/SKI_combinator_calculus

Helen
  • 87,344
  • 17
  • 243
  • 314
1

in perl:

`$0`

As a matter of fact, this will work with any shell that supports the backquote-command syntax and stores its own name in $0

dsm
  • 10,263
  • 1
  • 38
  • 72
  • Or, perhaps, "do $0"? *goes and tries* – C. K. Young Sep 18 '08 at 07:01
  • I was going to leave your answer be, however, you've edited it enough times that I should speak. :-P What some posters have mentioned is that this is more a process-table overflow, than a stack overflow as such. Some people have posted fork bombs in this thread too, which may interest you. :-) – C. K. Young Sep 18 '08 at 09:57
1

False:

[1][1]#

(False is a stack language: # is a while loop that takes 2 closures, a conditional and a body. The body is the one that causes the overflow).

Aardappel
  • 5,559
  • 1
  • 19
  • 22
1

A better lua solution:

function c()c()end;

Stick this into SciTE or an interactive command prompt and then call it. Boom!

RCIX
  • 38,647
  • 50
  • 150
  • 207
0

OCaml

let rec f l = f l@l;;

This one is a little different. There's only one stack frame on the stack (since it's tail recursive), but it's input keeps growing until it overflows the stack. Just call f with a non empty list like so (at the interpreter prompt):

# f [0];;
Stack overflow during evaluation (looping recursion?).
Graphics Noob
  • 9,790
  • 11
  • 46
  • 44
0

Even though it doesn't really have a stack...

brainf*ck 5 char

+[>+]
Graphics Noob
  • 9,790
  • 11
  • 46
  • 44
0

Z80 assembly language...

.org 1000
loop: call loop

this generates 3 bytes of code at location 1000....

1000 CD 00 10

Tim Ring
  • 1,845
  • 1
  • 20
  • 27
0

ruby (again):

def a(x);x.gsub(/./){a$0};end;a"x"

There are plenty of ruby solutions already but I thought I'd throw in a regexp for good measure.

finnw
  • 47,861
  • 24
  • 143
  • 221
0

Another Windows Batch file:

:a
@call :a
Carlos Gutiérrez
  • 13,972
  • 5
  • 37
  • 47
0
main(){
   main();
}

Plain and nice C. Feels quite Intuitive to me.

N 1.1
  • 12,418
  • 6
  • 43
  • 61
0

Fortran, 13 and 20 chars

real n(0)
n(1)=0
end

or

call main
end

The second case is compiler-dependent; for GNU Fortran, it will need to be compiled with -fno-underscoring.

(Both counts include required newlines)

F'x
  • 12,105
  • 7
  • 71
  • 123
0

Haskell:

main = print $ x 1 where x y = x y + 1
jkramer
  • 15,440
  • 5
  • 47
  • 48
0

Dyalog APL

fib←{
    ⍵∊0 1:⍵
    +/∇¨⍵-1 2
}
wash
  • 497
  • 4
  • 7
0
int main(void) { return main(); }
Daniel Băluţă
  • 1,255
  • 11
  • 13
  • Fail, your answer can be tail-call optimised. :-P (Compiler turns that effectively into `goto _main`, where `_main` is the global symbol corresponding to your main function.) – C. K. Young Jun 13 '10 at 20:53
0

Python:

import sys  
sys.setrecursionlimit(sys.maxint)  
def so():  
    so()  
so()
sth
  • 222,467
  • 53
  • 283
  • 367
Artur Gaspar
  • 4,407
  • 1
  • 26
  • 28
0

JavaScript (17 Bytes)

eval(t="eval(t)")

VB Script (25 Bytes)

t="Execute(t)":Execute(t)
st0le
  • 33,375
  • 8
  • 89
  • 89
0

Prolog

This program crashes both SWI-Prolog and Sicstus Prolog when consulted.

p :- p, q.
:- p.
Kaarel
  • 10,554
  • 4
  • 56
  • 78
0

Tail call optimization can be sabotaged by not tail calling. In Common Lisp:

(defun f () (1+ (f)))
Svante
  • 50,694
  • 11
  • 78
  • 122
0

C++:

int overflow(int n)
{
    return overflow(1);
}
Niyaz
  • 53,943
  • 55
  • 151
  • 182
0
int main(){
    int a = 20;
    return main();
}
Agnel Kurian
  • 57,975
  • 43
  • 146
  • 217
0

JavaScript:

function i(){ i(); }
i();


C++ Using a function-pointer:
int main(){
   int (*f)() = &main;
   f();
}
Huppie
  • 11,263
  • 4
  • 32
  • 34
  • @danb, I did try that but Rhino didn't want to compile it. – Huppie Sep 15 '08 at 12:19
  • new function i(){i()}(); works. still not shorter of course... – asksol Sep 15 '08 at 12:31
  • As I commented in the comment to Vulcan Eager's post the C++ version is invalid, according to C++98 3.6.1.3 "The function main shall not be used within a program". – Motti Sep 15 '08 at 13:59
  • @Motti: Shame on Microsoft for compiling it just fine without errors in VS8 ;-) – Huppie Sep 15 '08 at 14:42
  • @Huppie - i'd venture to guess that this is a no-diagnostic-required error, much as is stack overflows to begin with. !(code compiling -> code correct). – Aaron Sep 18 '08 at 09:59
0

C#, done in 20 characters (exclusing whitespace):

int s(){
    return s();
}
GateKiller
  • 74,180
  • 73
  • 171
  • 204
0

Clarion:

Poke(0)
Sean Cameron
  • 325
  • 3
  • 8
  • Is there any publicly available documentation on how Clarion works? – C. K. Young Sep 15 '08 at 13:14
  • www.softvelocity.com has a fair amount of information, and the Clarion public newsgroup (comp.lang.clarion) has a wealth of information and an active community (although the newsgroup on news.softvelocity.com is the primary group and doesn't seem to be typically be synchronized with other servers). – Sean Cameron Feb 13 '09 at 09:30
0

I tried to do it in Erlang:

c(N)->c(N+1)+c(N-1).
c(0).

The double invocation of itself makes the memory usage go up O(n^2) rather than O(n).

However the Erlang interpreter doesn't appear to manage to crash.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

recursion is old hat. here is mutual recursion. kick off by calling either function.

a()
{
    b();
}
b()
{
    a();
}

PS: but you were asking for shortest way.. not most creative way!

Kinjal Dixit
  • 7,777
  • 2
  • 59
  • 68
  • Which language is this? If it's a dynamic language, then tail-call optimisation can apply; if it's C, and you're relying on implicit int, the lack of a return value is undefined behaviour. Using "return a()" and "return b()" would also be subject to tail call optimisation. :-P – C. K. Young Sep 15 '08 at 13:11
0

On the cell spus, there are no stack overflows, so theres no need for recursion, we can just wipe the stack pointer.

asm("andi $1, $1, 0" );

0

PHP - recursion just for fun. I imagine needing a PHP interpreter takes it out of the running, but hey - it'll make the crash.

function a() { a(); } a();
JWHEAT
  • 129
  • 4
0
//lang = C++... it's joke, of course
//Pay attention how 
void StackOverflow(){printf("StackOverflow!");}
int main()
{
    StackOverflow(); //called StackOverflow, right?
}
bgee
  • 989
  • 2
  • 13
  • 19
0

Perl in 10 chars

sub x{&x}x

Eventually uses up all available memory.

davidnicol
  • 41
  • 6
0

MS-DOS batch:

copy CON so.bat
so.bat
^Z
so.bat
davidnicol
  • 41
  • 6
  • Wait, you have to say "Call so.bat". Running a batch file without call is like using exec, if I remember right. :-P – C. K. Young Sep 15 '08 at 23:04
0

C# with 27 non-whitespace characters - includes the call.

Action a = null;
a = () => a();
a();
Amy B
  • 108,202
  • 21
  • 135
  • 185
0

bash: Only one process

\#!/bin/bash
of() { of; }
of
Helen
  • 87,344
  • 17
  • 243
  • 314
0

Pretty much any shell:

sh $0

(5 characters, only works if run from file)

  • sh $0& sh $0; # system crash (stop it with kill -9 -1 in another shell as the same user) – BCS Apr 24 '09 at 19:47
0

Five bytes in 16-bit asm which will cause a stack overflow.

push cs
push $-1
ret
Jonas Engström
  • 5,015
  • 3
  • 37
  • 36
0

VB.Net

Function StackOverflow() As Integer
    Return StackOverflow()
End Function
Kibbee
  • 65,369
  • 27
  • 142
  • 182
0

For Fun I had to look up the Motorolla HC11 Assembly:

              org           $100
Loop    nop
          jsr            Loop
PersistenceOfVision
  • 1,275
  • 11
  • 13
0

Not very short, but effective! (JavaScript)

setTimeout(1, function() {while(1) a=1;});
Thevs
  • 3,189
  • 2
  • 20
  • 32
0

I think it's cheating I've never played before ;) but here goes

8086 assembler:

org Int3VectorAdrress ;is that cheating?

int 3

1 byte - or 5 characters that generate code, what say you?

Despatcher
  • 1,745
  • 12
  • 18
  • Hahaha, nice try. I think to get away with this, you'd have to set the int 3 vector address to something suitable first, and that'd cost you some code bytes too. :-P – C. K. Young Sep 15 '08 at 23:19
0

Ruby, albeit not that short:

class Overflow
    def initialize
        Overflow.new
    end
end

Overflow.new
RFelix
  • 11
  • 4
0

In C#, this would create a stackoverflow...

static void Main()
{
    Main();
}
Helen
  • 87,344
  • 17
  • 243
  • 314
user11039
  • 854
  • 2
  • 9
  • 17
0

why not

mov sp,0

(stack grows down)

Helen
  • 87,344
  • 17
  • 243
  • 314
mike511
  • 1,685
  • 4
  • 16
  • 18
0

In a PostScript file called so.ps will cause execstackoverflow

%!PS
/increase {1 add} def
1 increase
(so.ps) run
Mark Nold
  • 5,638
  • 7
  • 31
  • 33
0

Meta problem in D:

class C(int i) { C!(i+1) c; }
C!(1) c;

compile time stack overflow

BCS
  • 75,627
  • 68
  • 187
  • 294
0

Actionscript 3: All done with arrays...

var i=[];
i[i.push(i)]=i;
trace(i);

Maybe not the smallest but I think it's cute. Especially the push method returning the new array length!

defmeta
  • 1,322
  • 3
  • 11
  • 19
  • If you replace `trace(i);` with `console.log(i);` it's also valid JavaScript code in Chrome or Firefox with Firebug. – Na7coldwater Jul 07 '10 at 23:24
0

In x86 assembly, place a divide by 0 instruction at the location in memory of the interrupt handler for divide by 0!

0
_asm t: call t;
Tolgahan Albayrak
  • 3,118
  • 1
  • 25
  • 28
-1

Ruby:

def i()i()end;i()

(17 chars)

-1

Prolog

p:-p.

= 5 characters

then start it and query p

i think that is quite small and runs out of stack in prolog.

a query of just a variable in swi prolog produces:

?- X. % ... 1,000,000 ............ 10,000,000 years later % % >> 42 << (last release gives the question)

and here is another bash fork bomb: :(){ :|:& };:

WaldWolf
  • 408
  • 3
  • 5
  • 1
    It doesn't run out of stack, at least in SWI-Prolog. It's tail recursion. What does run out of stack is: "assert(p :- (p, q)), assert(q). p." – Kaarel Feb 24 '09 at 21:02
-1

I think this will work in Java (untried):

enum A{B.values()}
enum B{A.values()}

Should overflow in static initialization before it even gets the chance to fail due to a lack of main(String[]).

Daniel Spiewak
  • 54,515
  • 14
  • 108
  • 120
-4
Redmond.Microsoft.Core.Windows.Start()
Helen
  • 87,344
  • 17
  • 243
  • 314
Oscar Cabrero
  • 4,168
  • 8
  • 29
  • 49