# Question
Title: Weirdest way to produce a stack overflow
As a programmer you certainly know the error of a stack overflow due to an obvious recursion. But there are certainly many weird and unusual ways to get your favourite language to spit that error out.

Objectives:

1. Must cause a stack overflow which is clearly visible on the error output.
2. Not allowed to use an obvious recursion.

Examples of invalid programs:

```
// Invalid, direct obvious recursion.
methodA(){ methodA(); }

```

```
// Invalid, indirect, but obvious recursion.
methodA(){ methodB(); }
methodB(){ methodA(); }

```

The most creative ways are the best as this a . I.e, avoid boring obvious answers like this:

```
throw new StackOverflowError(); // Valid, but very boring and downvote-deserving.

```

Even though I accepted an answer now, adding more answers is still okay :)

# Answer
## Python

```
import sys
sys.setrecursionlimit(1)

```

This will cause the interpreter to fail immediately:

```
$ cat test.py
import sys
sys.setrecursionlimit(1)
$ python test.py
Exception RuntimeError: 'maximum recursion depth exceeded' in <function _remove at 0x10e947b18> ignored
Exception RuntimeError: 'maximum recursion depth exceeded' in <function _remove at 0x10e8f6050> ignored
$

```

Instead of using recursion, it just shrinks the stack so it will overflow immediately.
> 224 votes

# Answer
# Python

```
import webbrowser
webbrowser.open("http://stackoverflow.com/")

```
> 189 votes

# Answer
## C / Linux 32bit

```
void g(void *p){
        void *a[1];
        a[2]=p-5;
}
void f(){
        void *a[1];
        g(a[2]);
}
main(){
        f();
        return 0;
}

```

Works by overwriting the return address, So `g` returns to the point in `main` before calling `f`. Will work for any platform where return addresses are on the stack, but may require tweaks.

Of course, writing outside of an array is **undefined behavior**, and you have no guarantee that it will cause a stack overflow rather than, say, paint your mustache blue. Details of platform, compiler and compilation flags may make a big difference.
> 131 votes

# Answer
## JavaScript / DOM

```
with (document.body) {
    addEventListener('DOMSubtreeModified', function() {
        appendChild(firstChild);
    }, false);

    title = 'Kill me!';
}

```

If you want to kill your browser try that out in the console.
> 107 votes

# Answer
# Java

Saw something like this somewhere around here:

**Edit:** Found where I saw it: Joe K's answer to *Shortest program that throws StackOverflow Error*

```
public class A {
    String val;
    public String toString() {
        return val + this;
    }

    public static void main(String[] args) {
        System.out.println(new A());
    }
}

```

That can confuse some Java beginners. It simply hides the recursive call. `val + this` becomes `val + this.toString()` because `val` is a String.

See it run here: http://ideone.com/Z0sXiD
> 91 votes

# Answer
# C

Quite easy:

```
int main()
{
    int large[10000000] = {0};
    return 0;
}

```
> 77 votes

# Answer
# Non-recursive stack overflow in C

Calling convention mismatch.

```
typedef void __stdcall (* ptr) (int);

void __cdecl hello (int x) { }

void main () {
  ptr goodbye = (ptr)&hello;
  while (1)
    goodbye(0);
}

```

Compile with `gcc -O0`.

`__cdecl` functions expect the caller to clean up the stack, and `__stdcall` expects the callee to do it, so by calling through the typecast function pointer, the cleanup is never done -- `main` pushes the parameter onto the stack for each call but nothing pops it and ultimately the stack fills.
> 63 votes

# Answer
I was frustrated by the fact that java 7 and java 8 are immune to my evil code in my previous answer. So I decided that a patch for that was necessary.

Success! I made `printStackTrace()` throw a `StackOverflowError`. `printStackTrace()` is commonly used for debugging and logging and no one reasonably suspects that it could be dangerous. It is not hard to see that this code could be abused to create some serious security issues:

```
public class StillMoreEvilThanMyPreviousOne {
    public static void main(String[] args) {
        try {
            evilMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void evilMethod() throws Exception {
        throw new EvilException();
    }

    public static class EvilException extends Exception {
        @Override
        public Throwable getCause() {
            return new EvilException();
        }
    }
}

```

Some people may think that this is an obvious recursion. It is not. The `EvilException` constructor does not calls the `getCause()` method, so that exception can actually be thrown safely after all. Calling the `getCause()` method will not result in a `StackOverflowError` either. The recursion is inside JDK's normally-unsuspected `printStackTrace()` behaviour and whatever 3rd party library for debugging and logging that are used to inspect the exception. Further, it is likely that the place where the exception is thrown is very far from the place where it is handled.

Anyway, here is a code that does throw a `StackOverflowError` and contains no recursive method calls after all. The `StackOverflowError` happens outside the `main` method, in JDK's `UncaughtExceptionHandler`:

```
public class StillMoreEvilThanMyPreviousOneVersion2 {
    public static void main(String[] args) {
        evilMethod();
    }

    private static void evilMethod() {
        throw new EvilException();
    }

    public static class EvilException extends RuntimeException {
        @Override
        public Throwable getCause() {
            return new EvilException();
        }
    }
}

```

```
Exception: java.lang.StackOverflowError thrown from the UncaughtExceptionHandler in thread "main"

```
> 62 votes

# Answer
## JavaScript

```
window.toString = String.toLocaleString;
+this;

```
> 61 votes

# Answer
# Linux x86 NASM Assembly

```
section .data
    helloStr:     db 'Hello world!',10 ; Define our string
    helloStrLen:  equ $-helloStr       ; Define the length of our string

section .text
    global _start

    doExit:
        mov eax,1 ; Exit is syscall 1
        mov ebx,0 ; Exit status for success
        int 80h   ; Execute syscall

    printHello:
        mov eax,4           ; Write syscall is No. 4
        mov ebx,1           ; File descriptor 1, stdout
        mov ecx,helloStr    ; Our hello string
        mov edx,helloStrLen ; The length of our hello string
        int 80h             ; execute the syscall

    _start:
        call printHello ; Print "Hello World!" once
        call doExit     ; Exit afterwards

```

Spoiler:

> Forgetting to return from printHello, so we jump right into \_start again.
> 57 votes

# Answer
# C++ at compile time

```
template <unsigned N>
struct S : S<N-1> {};

template <>
struct S<0> {};

template
struct S<-1>;

```

```
$ g++ -c test.cc -ftemplate-depth=40000
g++: internal compiler error: Segmentation fault (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See  for instructions.

```

There is no recursion this source file, not one of the classes has itself as a base class, not even indirectly. (In C++, in a template class like this, `S<1>` and `S<2>` are completely distinct classes.) The segmentation fault is due to stack overflow after recursion in the compiler.
> 48 votes

# Answer
# Bash (Danger Alert)

```
while true
do
  mkdir x
  cd x
done

```

Strictly speaking, that will not directly stack overflow, but generates what may be labelled as "*a persistent stack-over-flow generating situation*": when you run this until your disk is full, and want to remove the mess with "rm -rf x", that one is hit.

It does not happen on all systems, though. Some are more robust than others.

### Big danger WARNING:

some systems handle this **very** badly and you may have a very hard time cleaning up (because "rm -rf" itself will run into a recusion problem). You may have to write a similar script to cleanup.

### Better try this in a scratch VM if not sure.

PS: the same applies, of course, if programmed or done in a batch script.
PPS: it may be interresting to get a comment from you, how your particular system behaves...
> 45 votes

# Answer
# Java

A nice one from Java Puzzlers. What does it print?

```
public class Reluctant {
    private Reluctant internalInstance = new Reluctant();

    public Reluctant() throws Exception {
        throw new Exception("I'm not coming out");
    }

    public static void main(String[] args) {
        try {
            Reluctant b = new Reluctant();
            System.out.println("Surprise!");
        } catch (Exception ex) {
            System.out.println("I told you so");
        }
    }
}

```

It actually fails with a StackOverflowError.

The exception in the constructor is just a red herring. This is what the book has to say about it:

> When you invoke a constructor, the **instance variable initializers run before the body of the constructor**. In this case, the initializer for the variable `internalInstance` invokes the constructor recursively. That constructor, in turn, initializes its own `internalInstance` field by invoking the Reluctant constructor again and so on, ad infinitum. These recursive invocations cause a `StackOverflowError` before the constructor body ever gets a chance to execute. Because `StackOverflowError` is a subtype of `Error` rather than `Exception`, the catch clause in `main` doesn't catch it.
> 43 votes

# Answer
# LaTeX

```
\end\end

```

The input stack overflows because `\end` repeatedly expands itself in an infinite loop, as explained here.

TeX fails with a `TeX capacity exceeded, sorry [input stack size=5000]` or similar.
> 41 votes

# Answer
# BF

Will eventually overflow the stack, just depends how long the interpreter makes the stack...

```
+[>+]

```
> 39 votes

# Answer
**On the Internet** (used by billion people/day)

```
Redirects, HTTP status code: 301

```

For example, on the Dell support website (no offense, sorry Dell):

If you remove the support TAG from the URL then it goes into ***infinite redirects***. In the following URL, ###### is any support TAG.

http://www.dell.com/support/drivers/uk/en/ukdhs1/ServiceTag/######?s=BSD&~ck=mn

I believe it's equivalent to a stack overflow.
> 32 votes

# Answer
## C#, at compile time

There are a number of ways to cause the Microsoft C# compiler to blow its stack; any time you see an "expression is too complex to compile" error from the C# compiler that is almost certainly because the stack has blown.

The parser is recursive descent, so any sufficiently deeply nested language structures will blow the stack:

```
 class C { class C { class C { ....

```

The expression parser is pretty smart about eliminating recursions on the side that is commonly recursed on. Usually:

```
x = 1 + 1 + 1 + 1 + .... + 1;

```

which builds an enormously deep parse tree, will not blow the stack. But if you force the recursion to happen on the other side:

```
x = 1 + (1 + (1 + (1 + ....+ (1 + 1))))))))))))))))))))))))))))))))))))))))))...;

```

then the stack can be blown.

These have the inelegant property that the program is very large. It is also possible to make the semantic analyzer go into unbounded recursions with a small program because it is not smart enough to remove certain odd cycles in the type system. (Roslyn might improve this.)

```
public interface IN<in U> {}
public interface IC<X> : IN<IN<IC<IC<X>>>> {}
...
IC<double> bar = whatever;
IN<IC<string>> foo = bar;  // Is this assignment legal?

```

I describe why this analysis goes into an infinite recursion here:

http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx

and for many more interesting examples you should read this paper:

http://research.microsoft.com/en-us/um/people/akenn/generics/FOOL2007.pdf
> 32 votes

# Answer
## PHP

A stackoverflow done with looping elements only.

```
$a = array(&$a);
while (1) {
    foreach ($a as &$tmp) {
        $tmp = array($tmp, &$a);
    }
}

```

Explanation (hover to see the spoiler):

> The program will segfault when the interpreter tries to garbage collect the `$tmp` array away (when reassigning `$tmp` here). Just because the array is too deep (self referencing) and then the garbage collector ends up in a recursion.
> 31 votes

# Answer
# Java

I did the exact opposite – a program that should obviously throw a stack overflow error, but doesn't.

```
public class Evil {
    public static void main(String[] args) {
        recurse();
    }

    private static void recurse() {
        try {
            recurse();
        } finally {
            recurse();
        }
    }
}

```

Hint: the program runs in O(2*n*) time, and *n* is the size of the stack (usually 1024).

From Java Puzzlers #45:

> Let's assume that our machine can execute 1010 calls per second and generate 1010 exceptions per second, which is quite generous by current standards. Under these assumptions, the program will terminate in about 1.7 × 10291 years. To put this in perspective, the lifetime of our sun is estimated at 1010 years, so it is a safe bet that none of us will be around to see this program terminate. Although it isn't an infinite loop, it might as well be.
> 30 votes

# Answer
# C#

First post, so please go easy on me.

```
class Program
{
    static void Main()
    {
        new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Invoke(null, null);
    }
}

```

This simply creates a stack trace, grabs the top frame (which will be our last call to `Main()`), gets the method, and invokes it.
> 30 votes

# Answer
# Java

* In Java 5, `printStackTrace()` enters an infinite loop.
* In Java 6, `printStackTrace()` throws `StackOverflowError`.
* In Java 7 and 8, it was fixed.

The crazy thing is that in Java 5 and 6, it does not comes from user code, it happens in JDK's code. No one reasonable suspects that `printStackTrace()` can be dangerous to execute.

```
public class Bad {
    public static void main(String[] args) {
        try {
            evilMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void evilMethod() throws Exception {
        Exception a = new Exception();
        Exception b = new Exception(a);
        a.initCause(b);
        throw a;
    }
}

```
> 26 votes

# Answer
# JavaScript: Non-recursive, iterative function mutation

```
var f = function() {
    console.log(arguments.length);
};

while (true) {
    f = f.bind(null, 1);
    f();
}

```

There's no recursion here at all. `f` will be repeatedly curried with more and more arguments until it can overflow the stack **in a single function call.** The `console.log` part is optional in case you want to see how many arguments it takes to do it. It also ensures that clever JS engines won't optimize this away.

Code-golf version in CoffeeScript, 28 chars:

```
f=->
do f=f.bind f,1 while 1

```
> 16 votes

# Answer
# C# with an epic fail

```
using System.Xml.Serialization;

[XmlRoot]
public class P
{
    public P X { get { return new P(); } set { } }
    static void Main()
    {
        new XmlSerializer(typeof(P)).Serialize(System.Console.Out, new P());
    }
}

```

The way it fails is epic, it blew my mind completely:

It is just one frame of a seemingly infinite tripping series of strange images.

This has got to be the weirdest thing ever. Can anybody explain? Apparently, the ever increasing amount of spaces used for indentation cause those white blocks to appear. It happens on a Win7 Enterprise x64 with .NET 4.5.

I haven't actually seen the end of it yet. If you replace `System.Console.Out` with `System.IO.Stream.Null`, it dies pretty fast.

The explanation is pretty simple. I make a class which has a single property, and it always returns a new instance of its containing type. So it's an infinitely deep object hierarchy. Now we need something which tries to read through that. That's where I use the `XmlSerializer`, which does just that. And apparently, it uses recursion.
> 14 votes

# Answer
## bash

```
_(){ _;};_

```

While many might recognize that the recursion is *obvious*, but it seems pretty. No?

Upon execution, you are guaranteed to see:

```
Segmentation fault (core dumped)

```
> 13 votes

# Answer
## Haskell

(sad but true until at least `ghc-7.6`, though with `O1` or more it'll optimise the problem away)

```
main = print $ sum [1 .. 100000000]

```
> 12 votes

# Answer
# Smalltalk

This creates a new method on the fly, which
creates a new method on the fly, which
creates a new method on the fly, which
...
...
..
and then transfers to it.

An extra little spice comes from stressing stack memory AND heap memory at the same time, by creating both a longer and longer method name, and a huge number as receiver, as we fall down the hole... (but the recursion hits us first).

compile in Integer:

```
downTheRabbitHole
    |name deeperName nextLevel|

    nextLevel := self * 2.
    name := thisContext selector.
    deeperName := (name , '_') asSymbol.
    Class withoutUpdatingChangesDo:[
        nextLevel class
            compile:deeperName , (thisContext method source copyFrom:name size+1).
    ].
    Transcript show:self; showCR:' - and down the rabbit hole...'.
    "/ self halt. "/ enable for debugging
    nextLevel perform:deeperName.

```

then jump, by evaluating `"2 downTheRabbitHole"`...
...after a while, you'll end up in a debugger, showing a RecursionException.

Then you have to cleanup all the mess (both SmallInteger and LargeInteger now have a lot of wonderland code):

```
{SmallInteger . LargeInteger } do:[:eachInfectedClass |
    (eachInfectedClass methodDictionary keys
        select:[:nm| nm startsWith:'downTheRabbitHole_'])
            do:[:each| eachInfectedClass removeSelector:each]

```

or else spend some time in the browser, removing alice's wonderland.

Here is some from the head of the trace:

```
2 - and down the rabbit hole...
4 - and down the rabbit hole...
8 - and down the rabbit hole...
16 - and down the rabbit hole...
[...]
576460752303423488 - and down the rabbit hole...
1152921504606846976 - and down the rabbit hole...
2305843009213693952 - and down the rabbit hole...
[...]
1267650600228229401496703205376 - and down the rabbit hole...
2535301200456458802993406410752 - and down the rabbit hole...
5070602400912917605986812821504 - and down the rabbit hole...
[...]
162259276829213363391578010288128 - and down the rabbit hole...
324518553658426726783156020576256 - and down the rabbit hole...
[...]
and so on...

```

PS: the "withoutUpdatingChangesFile:" was added to avoid having to cleanup Smalltalk's persistent change-log file afterwards.

PPS: thanks for the challenge: thinking about something new and innovative was fun!

PPPS: I like to note that some Smalltalk dialects/versions copy overflowing stack frames to the heap - so these may run into an out-of-memory situation instead.
> 12 votes

# Answer
## C#

Really big `struct`, no recursion, pure C#, not unsafe code.

```
public struct Wyern
{
    double a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
}
public struct Godzilla
{
    Wyern a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
}
public struct Cyclops
{
    Godzilla a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
}
public struct Titan
{
    Cyclops a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
}
class Program
{
    static void Main(string[] args)
    {
        // An unhandled exception of type 'System.StackOverflowException' occurred in ConsoleApplication1.exe
        var A=new Titan();
        // 26×26×26×26×8 = 3655808 bytes
        Console.WriteLine("Size={0}", Marshal.SizeOf(A));
    }
}

```

as a kicker it crashes the debug windows stating that `{Cannot evaluate expression because the current thread is in a stack overflow state.}`

---

And the generic version (thanks for the suggestion NPSF3000)

```
public struct Wyern<T>
    where T: struct
{
    T a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
}

class Program
{
    static void Main(string[] args)
    {
        // An unhandled exception of type 'System.StackOverflowException' occurred in ConsoleApplication1.exe
        var A=new Wyern<Wyern<Wyern<Wyern<int>>>>();
    }
}

```
> 12 votes

# Answer
# Starting reply using SnakeYAML

```
class A
{

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

```

Edit: ungolfed it

Its up to the reader to find out how that works :P (tip: stackoverflow.com)

By the way: the recursion is dynamically made by SnakeYAML (you will notice if you know how it detects the fields it serializes and look then in `Point`'s sourcecode)

Edit: telling how that one works:

SnakeYAML looks for a pair of `getXXX` and `setXXX` mthod with same name for `XXX` and return type of the getter is same as parameter of setter; and surprisingly the `Point` class has a `Point getLocation()` and `void setLocation(Point P)` which returns itself; SnakeYAML doesn't notice it and recurses on that quirk and StackOverflows. Discovered that one when working with them inside a `HashMap` and asking on stackoverflow.com on it.
> 11 votes

# Answer
## C#

Faulty implementation of overriden `==` operator:

```
public class MyClass
{
    public int A { get; set; }

    public static bool operator ==(MyClass obj1, MyClass obj2)
    {
        if (obj1 == null)
        {
            return obj2 == null;
        }
        else
        {
            return obj1.Equals(obj2);
        }
    }

    public static bool operator !=(MyClass obj1, MyClass obj2)
    {
        return !(obj1 == obj2);
    }

    public override bool Equals(object obj)
    {
        MyClass other = obj as MyClass;
        if (other == null)
        {
            return false;
        }
        else
        {
            return A == other.A;
        }
    }
}

```

One might say it's obvious that `operator==` calls itself by using the `==` operator, but you usually do not think that way about `==`, so it's easy to fall into that trap.
> 11 votes

# Answer
## C#

wrongly implemented property getter

```
class C
{
   public int P { get { return P; } }
}

static void Main()
{
   int p = new C().P;
}

```
> 10 votes

# Answer
# Java

```
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class HiddenStackOverflow extends JPanel implements MouseMotionListener {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("Animate Circle around Mouse Pointer");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new HiddenStackOverflow());
                frame.setVisible(true);
            }

        });
    }
    int x, y;

    public HiddenStackOverflow() {
        this.addMouseMotionListener(this);
        x = y = 0;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paint(g);
        g.fillOval(x - 50, y - 50, 100, 100);
    }

    @Override
    public void mouseDragged(MouseEvent me) {
        mouseMoved(me);
    }

    @Override
    public void mouseMoved(MouseEvent me) {
        x = me.getX();
        y = me.getY();
        repaint();
    }
}

```

This is a mistake that I actually made. Do not get `paint` and `paintComponent` mixed up.

If the `super.paint(g)` in method `paintComponent` were correctly written as `super.paintComponent(g)`, this program will continuously draw a black circle around the mouse pointer.

---

In response to some comments claiming this is obvious recursion, this is why I consider this not obvious:

* I occasionally make this mistake (made it often when I first started coding Swing).
* Rely's on "hidden code" (hidden in Swing and AWT) to create the recursion.
* calls the superclass method, not the "this" class.
> 7 votes

# Answer
## JavaScript - not a single expression

```
{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{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}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}

```

**Here is why it works**
> 6 votes

# Answer
## Java

They always tell you not to reinvent the wheel, so I used collections from `java.util`.

```
Set<Object> s = new HashSet<>();
s.add(s);
s.add(s);

```

And here's a simple list implementation extending the built-in `java.util.AbstractList`:

```
public class MyList<E> extends AbstractList<E> {

    private Object[] contents;

    public static void main(String[] args) {
        MyList<String> list = new MyList<>( "Roses", "are", "red" );
        System.out.println( list );
    }

    public MyList( E... fill ){
        contents = new Object[fill.length];
        for( int i=0; i<fill.length; i++ )
            contents[i] = fill[i];
    }

    @Override
    public E get(int i) {
        return (E)contents[i];
    }

    @Override
    public int size() {
        int i = 0;
        for( E e : this ) ++i;
        return i;
    }
}

```
> 5 votes

# Answer
## C#

Value types are created on the stack and stacks are usually 1 MB in size, so a simple struct will do...

```
using System.Runtime.InteropServices;
namespace N
{
    [StructLayout(LayoutKind.Explicit)]
    struct A
    {
        [FieldOffset(0xFFFFC)]
        public int a;
    }

    class P
    {
        static void Main()
        {
             A a= new A();
             Console.WriteLine(a.a);
        }
    }
}

```

I think it's even better if it comes a bit more subtle:

```
using System.Runtime.InteropServices;
using Debug=System.Console;
namespace N
{
    [StructLayout(LayoutKind.Explicit)]
    struct Console
    {
        [FieldOffset(0xFFFFC)] public int WriteLine;
    }

    class P
    {
        static void Main()
        {
            var console= new Console();
            Debug.WriteLine(console.WriteLine);
        }
    }
}

```
> 5 votes

# Answer
## C + GCC inline assembly

Same idea as Michael Ehrenreich's answer.

```
int f() {
        printf("Hello, world\n");
        asm(".section return");
}
asm(".previous");

int main() {
        f();
        return 0;
}

```

The return from `f` is moved to another section, and not executed.
> 4 votes

# Answer
# C, POSIX

```
#include <signal.h>
#include <stdlib.h>

void
foo(int sig)
{
        *(int *)sig = sig;
}

int
main(int argc, char **argv)
{
        struct sigaction sa;

        sa.sa_handler = foo;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = SA_NODEFER;
        sigaction(SIGSEGV, &sa, NULL);
        foo(42);

        return 0;
}

```

Should work on all POSIX systems. Only tested on MacOS and Linux. The final crash is because of a stack overflow even though there isn't really a way for the system to tell you it was one. Throw the core dump into a debugger if you don't believe that.
> 4 votes

# Answer
# Android / XML drawable

Save as `drawable/ololo.xml` and open in IntelliJ IDEA editor. It will display `java.lang.StackOverflowError`.

```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ololo"/>
</selector>

```
> 4 votes

# Answer
## Java

Picked up from here, it causes an `StackOverflowError` in the compiler:

```
class T { }
class N<Z> { }
class C<X> extends N<N<? super C<C<X>>>> {
  N<? super C<T>> cast(C<T> c) { return c; }
}

```
> 4 votes

# Answer
# EcmaScript 6 (only 19 bytes!):

```
atob(...Array(9e5))

```

It uses absolutely **no** recursion, and it's a fully-valid program!
> 4 votes

# Answer
# Python

This is one I've seen in practice, by accident:

```
class test(object):
    mainvalue=1
    def __getattribute__(self,attrname):
        return self.mainvalue

print test().blah

```

The catch is that, if you define `__getattr__` instead of `__getattribute__`, it works exactly as expected (it prints 1)
> 4 votes

# Answer
**C#**

```
var x = "Joel Spolsky";
var y = "Jeff Atwood";

var stackOverflow = x + y;

```

(Actual program output may vary)
> 4 votes

# Answer
# C (via ATL)

```
#include <AtlBase.h>
int main() {
     for(;;)
         printf("%s\n", W2CA("STACKOVERFLOW"));
     return 0;
}

```

Even for people who do code C, this looks like it simply loops forever printing "STACKOVERFLOW" to the screen. Turns out the W2CA is a macro that behind-the-scenes allocates stack memory which isn't released until the function returns. If you use it in a loop, a stack-overflow is a common (usually highly unexpected) result. Microsoft eventually deprecated this macro for this problem. This is effectively the same as Ruslan's answer, except less obvious what's going on.
> 4 votes

# Answer
# dc

With dc(1) in OpenBSD 5.5, adding a *comment* or *whitespace* to a program may overflow the stack.

Both of these programs have obvious recursion. They are infinite loops, and all loops in dc are tail-recursive. The **surprise** is that the first program *never* overflows:

```
[lwx]dswx

```

The second program *does* overflow:

```
[
 lw x   # loop forever
] d sw x

```

The *only* difference is that the second program has extra comments and whitespace. OpenBSD dc optimizes tail recursion only when the tail call, such as `x`, is immediately before the end bracket `]`. So, the first program loops forever. In the second program, dc wants to return and run the commands between the `x` and the `]`, so dc overflows the call stack.

```
dc: recursion too deep: Cannot allocate memory

```

To prevent overflow, I must play *code golf* and delete all comments and whitespace between the `x` and the `]`.
> 4 votes

# Answer
## Batch

```
@call me Al
    ~ Paul Simon

```

Save to a file called `me.bat`. Or add the label `:me` at the start of this batch file and change `@call me Al` to `@call :me Al`.
> 3 votes

# Answer
## Batch

```
call _

```

Save it to a file `_.bat` and execute it!

The code, *per se*, doesn't make the recursion obvious. Upon executing, you'd see:

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

```
> 3 votes

# Answer
## Python

`fork`ing isn't recursion, right?

```
import os
while 1: os.fork()

```
> 3 votes

# Answer
# bash

```
#!/bin/bash

touch $'\x3b'
bash -c "echo $(ls ./*)"

```

### Usage

Save as `ls` (any other filename works as well), make executable and call as `./ls`.

### What it does

* `touch $'\x3b'` creates a file called `;`.
* `$(ls ./*)` gets replaced by contents of the current directory.

Example:

```
./; ./ls

```
* `bash -c "echo ./; ./ls"` executes the following in a subshell:

```
echo ./
./ls

```
> 3 votes

# Answer
## Common Lisp (GNU CLISP)

```
[1]> (lambda () (funcall *))
#<FUNCTION :LAMBDA NIL (FUNCALL *)>
[2]> (funcall *)

*** - Program stack overflow. RESET

```

### Explanation (see if you can figure it out first):

> The value of the variable variable `*` is the result of the last form evaluated at the prompt. Thus, `(funcall *)` says "call the last REPL result," and that happens to be `(lambda () (funcall *))` which is a function that calls the last REPL result, which *at that point* is itself.

There are lots of variations on this theme:

```
[7]> (setf (symbol-function '*) (lambda () (funcall *)))
#<FUNCTION :LAMBDA NIL (FUNCALL *)>
[8]> (*)

*** - Program stack overflow. RESET

```

A particularly devious one would be a function that "works" (does something that's not a stack overflow) at first, and then *later* overflows the stack. E.g., using `**` (which is the second to last REPL result):

```
[14]> (defun hello-world () (print 'hello-world))
HELLO-WORLD
[15]> (defun uh-oh () (funcall **))
UH-OH
[16]> (uh-oh)

HELLO-WORLD
HELLO-WORLD
[17]> (uh-oh)

*** - Program stack overflow. RESET

```
> 3 votes

# Answer
C#, no recursion. Requires unsafe code. Attempt to allocate an array that wont fit on the stack.

```
class Program {
    static unsafe void Main() {
        var b = stackalloc byte[0x100000];
    }
}

```
> 3 votes

# Answer
## J

As J is generally a weird language, probably one of the shortest:

```
    $:''
| stack error
|       $: ''

```

An even weirder one, using every printable, non-white-space ASCII character exactly once:

```
!"#%&()*+,-/:;<=>?@ACDEFGHIJKLMOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~&$:0123456789 NB.'
|stack error
|   !"#%&()*+,-/:;<=>?@ACDEFGHIJKLMOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{    |}~&$:123456789

```
> 3 votes

# Answer
## Lua

Using metatables frequently results in stack overflows :

```
a=setmetatable({},{__index=function(t,k)return t[k]end})
print(a[1]) -- index this table.

```
> 3 votes

# Answer
# Ruby

```
evil = "eval evil"
eval evil

```

This will cause `SystemStackError: stack level too deep`

```
1.9.3p448 :006 >
1.9.3p448 :007 >   evil = " eval evil"
 => " eval evil"
1.9.3p448 :008 >   eval evil
SystemStackError: stack level too deep
    from /usr/local/rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/irb/workspace.rb:80
Maybe IRB bug!
1.9.3p448 :009 >

```
> 3 votes

# Answer
## C

A simple recursion. But where's the recursive call?!

```
#include <stdio.h>
#include <errno.h>

void f(int errno) {
        if (errno==EINVAL) puts("EINVAL");
}

int *main() {
        f(main);
        return 0;
}

```

Solution:

> `errno.h` defines: `#define errno *(__errno_location())`
> When this is expanded in the parameter list, `f` is defined to get a function pointer parameter, named `__errno_location`.
> When this is expanded in the body, this function is called.
> Calling `f` with `main` as a parameter leads to endless recursion.

**EDIT**: The previous version crashed, but not because of a stack overflow. Fixed.
> 3 votes

# Answer
# Java

More API vodoo. This time, the stack trace doesn't hint where the overflow line is actually.

```
class SO extends JFrame
{
    public static void main(String[]a)
    {
        new SO().setVisible(true);

    }
    public SO()
    {
        setSize(100,100);
        DefaultListModel m = new DefaultListModel();
        JList l = new JList(m);
        m.addElement(m);
        add(l);
    }
}

```

That derp happened to me once while programming some GUI stuff and I didn't knew where it was from
> 2 votes

# Answer
# C#

Using fixed arrays and loading `struct` into the stack for an operation.

```
public unsafe struct Godzilla
{
    public const int Size = 40900;
    fixed double data[Size];
    public Godzilla(double init)
    {
        fixed(double* ptr=data)
        {
            for(int i=0; i<Size; i++)
            {
                ptr[i]= init;
            }
        }
    }

    public void Add(Godzilla other)
    {
        fixed(double* ptr=data)
        {
            for(int i=0; i<Size; i++)
            {
                ptr[i]+=other.data[i];
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Godzilla A=new Godzilla(1.0);
        Godzilla B=new Godzilla(2.0);
        A.Add(B);
    }
}

```

It tries to load all the values on the stack and fails. Each struct is 8×40900 = 327,200 bytes long and when two of them get loaded into the stack it pukes.
> 2 votes

# Answer
# Java and no!!! recursion anywhere :P

```
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class E
{
    public static void main(String[]a)  //run with -Xmx=4G on a 64bit-OS with enough ram...
    {
        //Method m = new E().getClass().getMethod(null, parameterTypes);
        StringBuffer params = new StringBuffer();
        StringBuffer paramdef = new StringBuffer();
        int i=0;
        for (i=0; i < 1000000; i++)
        {
             params.append(i+",\n");
             paramdef.append("int param"+i+",\n");
        }
        params.append(i);
        paramdef.append("int param"+i);
        String classheader= "class E2{public static void lickme("+paramdef.toString()+"){} static{lickme("+params.toString()+");}}";
        //dump the string to a file to see what happens internally :P
        EU c2 = new EU("stackoverflow.com", classheader);
        JavaCompiler c = ToolProvider.getSystemJavaCompiler();
        c.getTask(null, null, null, null, null,Arrays.asList(new EU[]{c2})).call();
    }
    public static void nop(int... Overflower)
    {

    }
    public static class EU extends SimpleJavaFileObject {
           final String code;
           EU(String name, String code) {
               super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),
                     Kind.SOURCE);
               this.code = code;
           }

           @Override
           public CharSequence getCharContent(boolean ignoreEncodingErrors) {
               return code;
           }
       }
}

```

If you wonder what happens dump the string before it get compiled; java-eval ftw :P

If you swap that line `for (i=0; i < 1000000; i++)` to `for (i=0; i < 100 00000; i++)` it stackoverflows even with `-Xmx10G -Xss100M` as JVM parameters and peaks at just over 9GB RAM usage.

Trick used is sme weird handling f too many Method parameters inside the Compiler
> 2 votes

# Answer
**C# .NET** mishandling unhanded exceptions:

The idea can happen in many places, such as in ASP.NET, Winforms, WPF, well everywhere where you try to handle an unhanded exception and raise another error as a result. To me, this happened in a project where the error log was written in the database, but the database connection would fail, which in turn would raise another error.

Here is a simple windows forms application to illustrate the idea:

```
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Application.ThreadException += (sender, args) => WriteError("Unhandled Exception");
        }

        private void WriteError(string msg)
        {
            throw new Exception("Can't write!");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            throw new Exception("Overflow it!");
        }
    }
}

```
> 2 votes

# Answer
# TeX

```
\def~{\if~}~

```

At least the original TeX code crashes with a stack overflow here. Several (mostly newer) implementations take measures to avoid it, though, and bomb out with a nicer error message than "Segmentation Fault".
> 2 votes

# Answer
This can be easily achieved using a regex pattern like this in Java. Note that the required data length to reproduce this error may change depending on your architecture.

Replacing the pattern with a better `^([a-fA-F]|\\d)++$` successfully executes the code.

# Java

```
import java.util.regex.Pattern;

public class aRegexStackOverflow {
    public static void main(String [] whatIsThis) {
        try {
            String boom = "";
            for (int i=0; i<1292; i++)
                boom+=Integer.toHexString(0);
            System.out.println("Length: " + boom.length());
            if (Pattern.matches("^([a-fA-F]|\\d)+$", boom.trim()))
                System.out.println("This is working!");
            boom+=Integer.toHexString(0);
            System.out.println("Length: " + boom.length());
            if (Pattern.matches("^([a-fA-F]|\\d)+$", boom.trim()))
                System.out.println("This will never be printed...");
        }
        catch(StackOverflowError soe) {
            soe.printStackTrace();
        }
    }
}

```

---

**Output:**

```
Length: 1292
This is working!
Length: 1293
java.lang.StackOverflowError
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3692)
at java.util.regex.Pattern$Branch.match(Pattern.java:4502)
at ... //Goes on for a while tbh

```

---

**Explanation as stated in the comments by nhahtdh (thank you!)**

*Oracle's implementation of Pattern class uses recursion for matching greedy/lazy repetition of a non-trivial pattern. This explains the behavior. Some other JVM which reimplements the Pattern class (such as GNU classpath) and use data structure to simulate the recursion will not have this behavior.*

---

**Inspiration:** Oracle Bug Database (even if this is not an actual bug)
> 2 votes

# Answer
## Java:

The idea is to fill the stack with one huge stack frame, containning multiple local variables, rather then with multiple stack frames:

```
public class LocalVarOverFlow {

    public static void main(String args[]) {
        long
                l1 = 0, l2 = 0, l3 = 0, l4 = 0, l5 = 0,
                l6 = 0, l7 = 0, l8 = 0, l9 = 0, l10 = 0,
                l11 = 0, l12 = 0, l13 = 0, l14 = 0, l15 = 0,
                l16 = 0, l17 = 0, l18 = 0, l19 = 0, l20 = 0,

                ... ;
    }
}

```
> 2 votes

# Answer
# Java (Regex Compile)

The other Java regex answer (+1'd) SOEs on matching. Here's one that SOEs on compiling:

```
public class PatternSOE {
    public static void main(String[] args) {
        String rep = new String(new char[9999]);
        Pattern.compile(rep.replace("\0", "(") + "a" + rep.replace("\0", ")"));
    }
}

```

Basically builds and attempts to compile up a huge regex in the form:

```
 "((( ... (a) ... )))"

```

The regex parser recurses on each sub-group.
> 2 votes

# Answer
## Java

Recursive reflection:

```
import java.lang.reflect.Method;

public class StackOverflow {
    public static void main(String[] _) throws Exception {
        Method m = Method.class.getMethod("invoke", Object.class, Object[].class);
        Object[] args = { m, null };
        args[1] = args;
        m.invoke(m, args);
    }
}

```

I'd like to think that this code doesn't obviously cause a stack overflow, and I'd hope the 1.8MiB of stacktrace it generates counts as 'clearly visible'.

Idea shamelessly lifted from http://bugs.java.com/bugdatabase/view\_bug.do?bug\_id=4185411.
> 2 votes

# Answer
**C Buffer Overflow**

```
#include <stdio.h>
#include <math.h>

int main()
{
   char buff[20];
   sprintf(buff, "Value of Pi = %f", M_PI);
   return(0);
}

```
> 2 votes

# Answer
**PHP**

```
<?php
header("Location: {$_SERVER['PHP_SELF']}");

```

Navigating to this page produces this result:
> 2 votes

# Answer
**Apache mod\_rewrite done wrong**

```
RewriteEngine On
RewriteRule ^(.+)$ /$1.php [L]

```

The rule, which is supposed to map URLs such as `/about-us` to `/about-us.php`, ends up producing this error in Apache logs (the `L` flag does not help):

> Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
> 2 votes

# Answer
Although it's not a real stack overflow but effects are pretty much the same.

```
int main()
{
    asm("movl $0, %esp");
}

```

C++ (since there is no return from main) and i386-like cpus.

ESP is the stack pointer in i386 processor, by doing that, we're pointing the stack out of the memory reserved for it, something similar happens when recursion is involved - just without actually writing to it.

Notice that SIGSEGV is generated not when ESP is changed but when the the program uses the stack, so if we modify the code like this

```
#include <iostream>

void foo()
{
    std::cout << "hello";
}

int main()
{
    asm("movl $0, %esp");
    foo();
}

```

we will get the crash at:

```
Program received signal SIGSEGV, Segmentation fault.
main () at stack.cpp:11
11        foo();

```

The interesting thing about SO is that you cannot catch SIGSEGV signal by using signal() function since there no stack to call it, but you can provide alternate stack (eg heap allocated) to the sigaction function.
> 2 votes

# Answer
# Haskell

A joke I thought of a couple of years back:

```
import Control.Monad.Fix

main = print(fix error)

```

gives

```
"*** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: ... etc.

```

I'm not getting a stack overflow error, but maybe that is because the Glasgow Haskell Compiler uses lazy evaluation.

The function `fix :: (a -> a) -> a` gives the first fix point of the function error - `fix` applies a function to itself. In that sense it is plain and simple recursion. The function `error :: [Char] -> a` requires a string argument and returns something of any type. That is why it can serve as the argument to another error function.
> 2 votes

# Answer
# Python and the Y combinator

before someone else does it:

```
(lambda f: (lambda x: x(x))(lambda y: f(lambda : y(y)())))(lambda f: f)()

```

Please, if you don't know much about lambda calculus, don't downvote this solution because you believe that the recursive call is obvious; it isn't obvious at all. More precisely, `lambda x: x(x)` or `lambda : y(y)` or `lambda f: f` ARE NOT recursive calls but mere functions applying to functions.
> 2 votes

# Answer
# C with GCC extensions

```
int main() {
  goto *(void*)main;
  return 0;
}

```

This will compile without errors and without using any compiler flags when using GCC. GCC allows "computed gotos", where you can jump directly to a pointer. It doesn't look like the goto would cause a stack overflow, but GCC puts a preamble in the main() function that pushes one register to the stack, as can be seen in the produced assembler:

```
main:
  pushq %rbp
  movq  %rsp, %rbp
  movl  $main, %eax
  jmp   *%rax

```
> 2 votes

# Answer
## AppleSoft BASIC

```
0 GOSUB 0

```

Not so weird but worth mentioning...
> 1 votes

# Answer
# Java again :) Serializing FTW :P

```
public class C {
    public static class Ci implements Serializable {
        public Object o;
    }

    public static void main(String[] a) throws IOException, InterruptedException {
        List l = new ArrayList<>();
        ObjectOutputStream o = new ObjectOutputStream(new OutputStream(){
            public void write(int b) {/*DEVNULL*/}
        });

        Ci c = new Ci();
        Ci c2 = null;
        int i = 0;
        for (;;) {
            i++;
            if (i % 100000 == 0) {
                System.out.println("Serializing...");
                o.writeObject(c);
                o = new ObjectOutputStream(new OutputStream(){
                    public void write(int b) {/*DEVNULL*/}
                });
                Thread.sleep(1000);
            }

            if (false)
                break;

            c2 = c;
            c = new Ci();
            c.o = c2;
        }
    }
}

```

Googling a bit around should tell how this one works :P

The modulo operator is to reduce workload and speed the thing up.
> 1 votes

# Answer
# Go

I challenge anybody to see the bug, who doesn't already know where it is. I added a few (truthful) comments to explain the code to non-Goers.

Try to find it yourself, if you're so inclined, before reading the comment section below (where somebody will surely spoil it.)

Here is a link to the playground: http://play.golang.org/p/UwunxiXKP7

```
package main

import "fmt"

// Aim: to define an integer type that by default is printed in hex notation (0xab..)
type hexInt int

// Implementation of the Stringer interface, used by Println for conversion to string.
func (h hexInt) String() string {
    // "%#x" is the alternate form of "%x", which uses lowercase a-f and adds 0x in front.
    return fmt.Sprintf("%#x", h)
}

func main() {
    // Create a variable of type hexInt with the value 42 and print it.
    var h hexInt = 42
    fmt.Println(h)
}

```
> 1 votes

# Answer
## Python:

Using anonymous recursion. I'm not sure if this is too straight-forward or not, but there are no declared functions, so it seems potentially interesting.

```
(lambda f:f(f))(lambda f:f(f))

```
> 1 votes

# Answer
# C#

```
  public static int i
  {
      set { i = value; }
  }
  static void Main(string[] args)
  {
      i = 0;
  }

```
> 1 votes

# Answer
**Common problem in a Rails model**

```
after_save :bump_version

# a lot of code....

private

def bump_version
  create_new_version_record
  update_attribute(:version, version+1)
end

```
> 1 votes

# Answer
## Flash AS3

```
public class Work extends Sprite
{
    public function Work()
    {
        doIt();
    }

    private function doIt():void
    {
        noYouDoIt();
    }

    private function noYouDoIt():void
    {
        arguments.callee();
    }
}

```
> 1 votes

# Answer
Netware:

```
echo hello > file
cat file >> file

```

I discovered this (but did not use it) many decades ago. I mentioned it to someone, who did it on a Netware share. The share had no limits, and was also used for scratch space by the netware server itself.

The server filled with this one file end-to-end-to-end, crashed (due to running out of diskspace), and couldn't be brought back up until the file was removed. The file, of course, couldn't be removed until the server was running.
> 1 votes

# Answer
## Javascript

Tested in Chrome:

```
var a = Array(10000000);
(function(){}).apply(this, a);

```
> 1 votes

# Answer
**C#**

```
public abstract class A
{
  public int X {get { return -1; }}
  public virtual string Value(){ return "A"; }
}

public class B : A
{
  public new int X {get{ return 42; }}
  public override string Value() { return "B"; }
}

public class C : B
{
  // no recursion; returns -1
  public int XFromA {get { return ((A)this).X; }}

  // no recursion; returns 42
  public int XFromB {get { return ((B)this).X; }}

  // no recursion; returns "B"
  public override string Value() { return base.Value(); }

  // StackOverflowException
  public override string Value() { return ((A)this).Value(); }
}

```
> 1 votes

# Answer
**C**

```
void main()
{
    while(1)
        *(char*)alloca(1000)=0;
}

```

Funnily, without `=0` it will rotate indefinitely because it'll just subtract stack pointer without causing any stack accesses.
> 1 votes

# Answer
## Haskell

```
import Control.DeepSeq
makeFunc n = \input -> (newfunc input) `deepseq`
    unlines [ "Function number "++(show n)++"was called with "++input
            , "Now calling the next function."
            , newfunc input]
            where
                newfunc=makeFunc (n+1)

main=putStrLn ((  makeFunc (0::Double)  ) "Input")

```

In this, each function creates a new one, and calls it. Note that this is no recursion, in that no function call itself.
> 1 votes

# Answer
## excel vba

```
Private Sub Worksheet_Change(ByVal Target As Range)
[a1] = 1
End Sub

```

place code into any worksheet

stack will overflow (in vba, displayed as an out of memory error) as each change to the worksheet triggers another change.
> 1 votes

# Answer
Well just since I'm bored.

```
int main()
{
   char *ptr;
   ptr = &ptr - sizeof(ptr);
   while(1)
      *--ptr = 0;
}

```

Invokes undefined behavior that trips the guard page the same way a stack overflow does.
> 1 votes

# Answer
# Vim

```
:se maxf<tab>=0<CR>
:help<CR>

```

Produces `E132: Function call depth is higher than 'maxfuncdepth'`, vim's equivalent of a stack overflow. (Several times, actually)
> 1 votes

# Answer
ANS Forth:

```
0 >in 2dup ! !

```

which leads to:

```
$ gforth
Gforth 0.7.0, Copyright (C) 1995-2008 Free Software Foundation, Inc.
Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license'
Type `bye' to exit
0 >in 2dup ! !
:1: Stack overflow
0 >in 2dup >>>!<<< !
Backtrace:
$B71DF6EC r>
$B71D34A4 perform
$B71DD654 (search-wordlist)
$3
$0
$B71DD734 (vocfind)
$B71D34A4 perform
$B71D351C (search-wordlist)
$B71D3FF4 find-name

```

In fact, the 2nd `!` is never executed.

`>in` is an integer variable that contains the current position within the input line, the program attempts to write zero to `>in` two times, but after the first write (`!`) the input pointer is reset to the start of input line, and the 2nd pair of values is left on the stack...
> 1 votes

# Answer
Another one!

**Ruby**

```
class Foo
  def method_missing *args, &block
    foo
  end
end

Foo.new.stack_overflow!
SystemStackError: stack level too deep
        from /home/bbozo/.rvm/rubies/ruby-1.9.3-p286/lib/ruby/1.9.1/irb/workspace.rb:80
Maybe IRB bug!

```
> 1 votes

# Answer
# C#

This will stack overflow the CLR I think, and report that type could not be loaded.

```
public struct Titan
{
    public Pluto Data { get; set; }
}

public struct Pluto
{
    public Titan Data { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        //System.TypeLoadException was unhandled
        //Message="Could not load type 'ConsoleApplication1.Titan' from assembly 'ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'."
        //Source="ConsoleApplication1"
        //TypeName="ConsoleApplication1.Titan"
        //StackTrace:
        //     at ConsoleApplication1.Program.Main(String[] args)
        //     at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
        //     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
        //     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
        //     at System.Threading.ThreadHelper.ThreadStart()
        Titan t;
    }
}

```
> 1 votes

# Answer
## C: "Hello World" format

```
#include <stdio.h>
int main(){
    (*printf+285)("Hello World\n");
}

```

This is actually a recursive call that fails when the stack get too big, but it is definitely not an *obvious* one.
> 1 votes

# Answer
## PHP

```
$a = array('call_user_func_array', &$a);
$a[0]($a[0], $a);

Process exited with code 139.

```

Compatible from 4.3 to 5.6
> 1 votes

# Answer
**(C)Python**

```
eval("f("*99+")"*99)

```

Produces:

```
s_push: parser stack overflow
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    eval("f("*99+")"*99)
MemoryError

```
> 1 votes

# Answer
**Python**

```
>>> class C:
...     def __setattr__(self, k, v):
...             self.k = v
...
>>> C().x = 10
...
  File "<stdin>", line 3, in __setattr__
RuntimeError: maximum recursion depth exceeded while calling a Python object

```

`__getattribute__` will also do this in a similar way.
> 1 votes

# Answer
**Haskell**

I'm surprised nobody posted this already... Maybe it's too obvious?

```
data Foo = Bar

instance Eq Foo where

main = print (Bar == Bar)

```

Naturally, `Bar == Bar` *should* evaluate to `True`. So this program *should* just print "True" and then exit. However, that's not what the empty `instance Eq Foo` declaration does. ;-)
> 1 votes

# Answer
Java

StackOverflowError before main is even executed. No recursive functions required, good old initializers. Also one of the shortest Java programs:

```
public class _ { static { new _(); } { new _(); } public static void main(String[] _) {}}

```

Make sure this class isn't referenced anywhere in the codebase or you will get a StackOverflowError on load. Which also makes this really easy to hide anywhere.
> 1 votes

# Answer
**JAVA**

"B" overrides "foo()", but invokes "super.foo()". Because the overridden "foo()" in "A" is invoked by an instance of "B", the "this" reference is pointing to "B", not "A". Therefore, when I create another instance of "this", another "B" object is created.

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

   static class A {
        void foo() {
            try {
                this.getClass().newInstance();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class B extends A {
        B() { foo(); }

        void foo() { super.foo(); }
    }
}

```
> 1 votes

# Answer
# Scheme

```
((lambda (x) (x x)) (lambda (x) (+ 1 (x x))))

```

I claim this is not an obvious *recursion*.
> 1 votes

# Answer
A few months ago I ran into this stack overflow in C#, which took me a significant amount of time to track and figure out what was going on. Assuming you have a C# application with Aspose PDF installed:

```
Aspose.Pdf.Generator.Pdf pdf = new Pdf();
pdf.HtmlInfo.CharSet = "UTF-8";
pdf.BindHTML("<div><img src=\"myImage.jpg\" alt=\"broken!\" /></div>");
pdf.HtmlInfo.ImgUrl = @"C:\users\me\pictures";
pdf.Save(@"c:\output.pdf");

```

If "myImage.jpg" is more than about twice as tall as it is wide, the image will overflow the generated PDF page, and somewhere in obfuscated code this results in a stack overflow.
> 1 votes

# Answer
# Java

This code causes `StackOverflowError` on Oracle's JRE/JDK and OpenJDK. Basically, any JVM that uses the reference implementation for the class library.

```
import java.util.regex.*;
import java.text.*;

class G21114 {
    public static void main(String args[]) {
        StringBuffer buf = new StringBuffer();
        int c = 0;

        for (int i = Character.MIN_CODE_POINT; i < Character.MAX_CODE_POINT; i++) {
            if (Character.isDefined(i) && Character.getType(i) != Character.SURROGATE) {
                int codePoint[] = {i};
                String s = new String(codePoint, 0, codePoint.length);

                if (!Normalizer.normalize(s, Normalizer.Form.NFD).equals(s)) {
                    buf.append(s); buf.append(s); buf.append(s);
                    buf.append('a');
                    buf.append(s); buf.append(s);
                    c++;

                    if (c >= 300) break; // Don't need too many
                }
            }
        }

        System.out.println(buf.length());

        // try-catch to clearly show what is thrown
        try {
            Pattern.compile(buf.toString(), Pattern.CANON_EQ);
        } catch (PatternSyntaxException e) {
            System.out.println(e.getClass());
        } catch (Error e) {
            System.out.println(e.getClass());
        }
    }
}

```

This is based on the fact that the reference implementation implements the `Pattern.CANON_EQ` (canonical equivalence) mode by modifying the input string to create alternation between all the possible decompositions. The string is then compiled as per normal.

The construction works well on a single character, but if there are multiple decomposable character in a row, the construction goes amok and doesn't close non-capturing groups `(?:regex)` properly. Look at this bug report for the test case.

However, to cause `StackOverflowError`, the parentheses don't need to be balanced. The combination of letters I chose above happen to produce a series of many opening parentheses, which cause the recursive descent parser in Pattern class to exhaust the stack. The underlying cause is similar to ɲeuroburɳ's answer. However, the code above is more discrete in causing the `StackOverflowError` and depends on internal implementation of `Pattern` class.
> 1 votes

# Answer
## Java

```
public class Temp {
    public static void main(String[] args) throws Exception {
        Temp.class.getMethod("main", String[].class).invoke(null, new Object[]{null});
    }
}

```

Gives a bunch of weird stack traces and exceptions

* `InvocationTargetException` once with a gazillion times 'caused by `InvocationTargetException`'
* `InvocationTargetException` another gazillion times without stack trace, only `... 1024 more`
* finally ending in `StackOverflowError`

Also posted in Call a method without calling it
> 1 votes

# Answer
Lua:

```
setmetatable(_ENV, {__newindex = function(x, y) z = y; end});

test="Hello world!"

```
> 1 votes

# Answer
## Tcl

```
interp r {} 1
a

```

Uses the same trick that python uses (recursionlimit).
Calling a will result in a call to `unknown` which executes a lot of other stuff (which will fail)

And here an other one:

```
proc unknown {args} a
a

```
> 1 votes

# Answer
# Rant

```
[?[src]]

```

Allow me to explain.

`[src]` is a function that returns the source code of the current state object. Metapatterns (`[?...]`) generate their own source code, so the return value is different when `[src]` is called inside as opposed to outside. This is where things get rather weird...

When the code is executed, the metapattern generates a source. It calls `[src]`, which returns the metapattern's source code, which is just `[src]`. It jumps back to the original scope with this new code on the stack, and runs it again. This calls `[src]`, which returns `[?[src]]`. When this is executed, another metapattern is created. It generates the same code, until the entire allotted stack space is used up and all hell breaks loose.

Basically, the flow of the program looks like this:

* `[?[src]]`
    + `[src]`
        - `[?[src]]`
            * `[src]`
                + `[?[src]]`
                    - ...

... where indent depth represents stack size.

Try it online!
> 1 votes

# Answer
**Shell and HQ9+**

Assumes that there is an HQ9+ interpreter called hq9

crash\_things.sh:

```
hq9 $1 | crash_things

```

runs recursively, exits when the output is not a valid HQ9+ program.

evil\_code.sh:

```
hq9 QQ | crash_things

```

messes it up because the code doubles in length every time.
> 1 votes

# Answer
# Frege

Type this in the REPL at try.frege-lang.org

```
> foldr (+) 0 [1..]

```
> 0 votes

# Answer
# Delphi / Object Pascal

Not exactly weird, but technically deprecated and certainly without recursion.

```
  raise EStackOverflow.Create('Without recursion'); // deprecated warning

```

This raises the same stack overflow exception that would be raised by an actual stack overflow. Compiling the code results in `[dcc32 Warning]: W1000 Symbol 'EStackOverflow' is deprecated` warning because the `EStackOverflow` class is defined in `System.SysUtils` as deprecated presumably with the intention that it never be actually raised, but it is defined to make it easier to trap and handle a Stack Overflow (despite the fact you really can't do much to recover from a stack overflow).

You could suppress the warning by wrapping it in a compiler directive.
> 0 votes

# Answer
## Python

```
class I:
    def __init__(self, kids=[]):
        self.kids=kids
    def allkids(self):
        for ii in self.kids:
            ii.allkids()
jj = I()
jj.kids.append(I())
jj.allkids()

```

It dumps when you run it because of a mutable default argument

```
  ... more here ...
  File "foo.py", line 6, in allkids
    ii.allkids()
  File "foo.py", line 6, in allkids
    ii.allkids()
RuntimeError: maximum recursion depth exceeded
[mpenning@tsunanmi]$

```
> 0 votes

# Answer
# Java again.

Using too many parameters this time

```
public class M
{

    public static final int maxmethods=1024;
    public static void main(String[]a) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        StringBuffer paramvals = new StringBuffer();
        StringBuffer paramdecls = new StringBuffer();
        StringBuffer paramusages = new StringBuffer();
        String[] methodnames = new String[maxmethods];
        String[] methods = new String[maxmethods];
        int i=0;
        for (; i < maxmethods-1; i++)
        {
            methodnames[i] = "method"+i+"(";
            System.out.println(i);
            if(i<253){
            paramvals.append(i+",");
            paramusages.append("param"+i+",");
            paramdecls.append("int param"+i+",");}
        }
        i=maxmethods-1;
        methodnames[i] = "method"+i+"(";
        paramvals.append(255+"");
        paramusages.append("param"+255);
        paramdecls.append("int param"+255);
        for (int j = 0; j < methodnames.length-1; j++)
        {
            methods[j] = "public static void "+methodnames[j]+paramdecls+")\n{\n"+methodnames[j+1]+paramusages+");\n}";
        }
        methods[maxmethods-1] = "public static void "+methodnames[maxmethods-1]+paramdecls+")\n{\nSystem.out.println(\"This shouldnt be reached\");\n}";
        //fuckyou java
        StringBuilder finaL = new StringBuilder();
        finaL.append("public class F{\npublic static void main(String[]a){System.out.println(\"NOPPE\");}\n\nstatic{helper();}\n"+
                "public static void helper(){method0("+paramvals+");\n}\n//#######################################################+\n");
        for (String method : methods)
        {
            finaL.append(method);
        }
        finaL.append("}");
        new FileWriter(new File("F.java")).write((finaL+"").toCharArray());//Dump of srcfile generated
        EU c2 = new EU("F", finaL+"");
        JavaCompiler c = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager f = c.getStandardFileManager(null,null,null);
        c.getTask(null, f, null, null, null,Arrays.asList(new EU[]{c2})).call();
        //System.out.print(new File("").toURI().toURL());
        URLClassLoader u = new URLClassLoader(new URL[]{new File("").toURI().toURL()});
        Class fc = u.loadClass("F");
        fc.getMethod("helper", null).invoke(null, null);
    }
        public static class EU extends SimpleJavaFileObject {
           final String code;

           EU(String name, String code) {
               super(URI.create("string:///" + name.replace('.','/') + JavaFileObject.Kind.SOURCE.extension),
                     JavaFileObject.Kind.SOURCE);
               this.code = code;
           }
           @Override
           public CharSequence getCharContent(boolean ignoreEncodingErrors) {
               return code;
           }
       }
}

```

generated file is dumped in workdirecotry used while running; no endless recursion inside :P runtime compilation ftw :)

Edit: moved the method count to a constant
> 0 votes

# Answer
## Python

```
>>> def foo( N ):
    root = list()
    nest = root
    for i in range(N):
        nest.append( list() )
        nest = nest[0]
    return root

>>> nested(999)

Traceback (most recent call last):
  File "<pyshell#184>", line 1, in <module>
    nested(999)
RuntimeError: maximum recursion depth exceeded while getting the repr of a list

```
> 0 votes

# Answer
**Ruby**

```
class Fixnum
  def +(arg)
    self-arg
  end
  def -(arg)
    self+arg
  end
end

```

reopens the `Fixnum` class, defines addition as substraction and substraction as addition, then simply do:

```
3+2

```

and voila :)
> 0 votes

# Answer
# Batch

```
START http://stackoverflow.com
ECHO STACKOVERFLOW!
PAUSE > NUL

```

Sorry, I coudln't resist!

It fulfills rule 1 and 2 ;o
> 0 votes

# Answer
## Groovy

```
def getProperty(String p){ p2 }; p

```

Due to an undefined property, Groovy calls `getProperty` again.
> 0 votes

# Answer
# Python 2

Stack overflow caused by printing. Yes, the standard usual printing operation. It's SIGSEGV, not standard RuntimeError in CPython.

```
print reduce(lambda*s:s,range(100000))

```
> 0 votes

# Answer
We can do it with the worlds most convoluted javascript! I think it's a cheat since it is really just "obvious" recursion.

```
(function(f){
    return new function () {
        for(var i= 1; i<3;i++) {
        (function(i){this[i] =  this[f(i)] || function (arg) {
            return !arg || (this[f(i)] || this[i + 1]).apply(this, [f(arg)]);
    }}.bind(this))(f(i));
        }
}
})(function(i){return i === 1 ? i : i - 1;})[1](1);

```
> 0 votes

# Answer
# VB.NET

I found this when I did your basic merge sort when I came across a StackOverFlowError. I was so confuzzled I asked a SO question about it. Without going to the link, can you find the cause? The link. Obviously this sorting algorithm uses recursion, but that is not the *cause* of the error being thrown.

**Runner Class:**

```
Module Module1

    Sub Main()
        dim array = new integer(100){}
        dim random = new Random()
        for i=0 to 100
            array(i) = random.next()
        next
        dim sorter = new MergeSort()
        sorter.sort(array)
    End Sub
End Module

```

**MergeSort Class:**

```
public class MergeSort

    private numbers() as integer
    private helper() as integer

    private number as integer

    public sub sort(values as integer())
        me.numbers = values
        number = values.length
        me.helper = new integer(number) {}
        mergesort(0, number - 1)
    end sub

    private sub mergesort(low as integer, high as integer)
' check if low is smaller then high, if not then the array is sorted
        if (low < high)
  ' Get the index of the element which is in the middle
          dim middle as integer = low + (high - low) / 2
  ' Sort the left side of the array
          mergesort(low, middle)
  ' Sort the right side of the array
          mergesort(middle + 1, high)
  ' Combine them both
          merge(low, middle, high)
        end if
    end sub

    private sub merge(low as integer,middle as integer,high as integer)
    ' Copy both parts into the helper array
        for l = low to high
          helper(l) = numbers(l)
        next

        dim i as integer = low
        dim j as integer = middle + 1
        dim k as integer = low
    ' Copy the smallest values from either the left or the right side back
    ' to the original array
        while (i <= middle andalso j <= high)
          if (helper(i) <= helper(j))
            numbers(k) = helper(i)
            i+=1
          else
            numbers(k) = helper(j)
            j+=1
          end if
          k+=1
        end while

    ' Copy the rest of the left side of the array integero the target array
        while (i <= middle)
          numbers(k) = helper(i)
          k+=1
          i+=1
        end while
    end sub
end class

```
> 0 votes

# Answer
**Ruby**

```
puts Time.now

```

Presumably, someday many millions of years into the future, the current time will become so large that the computer will run out of memory.
> -1 votes

# Answer
The Ackermann function!

# Java

```
public class Ackermann {

   public static long ackermann(long m, long n) {
      if (m == 0) return n + 1;
      if (n == 0) return ackermann(m - 1, 1);
      return ackermann(m - 1, ackermann(m, n - 1));
   }

   public static void main(String[] args) {
      long M = Long.parseLong(args[0]);
      long N = Long.parseLong(args[1]);
      System.out.println(ackermann(M, N));
   }
}

```

(Shamelessly copied from http://introcs.cs.princeton.edu/java/75universality/Ackermann.java.html)

```
 % java Ackermann 3 8
 2045
 % java Ackermann 3 9
 StackOverflowError

```
> -3 votes

# Answer
## C

```
#include <stdio.h>

int main()
{
   main();
   return 0;
}

```
> -3 votes

---
Tags: popularity-contest, stack
---


title: Align the text to a block

text:
# Question
Title: Align the text to a block
# Task

Your task is to write whole program, which will align given input to a block of given size.

*Input:*

```
40
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

*Output:*

```
Lorem  ipsum dolor sit amet, consectetur
adipiscing  elit,  sed do eiusmod tempor
incididunt  ut  labore  et  dolore magna
aliqua.  Ut  enim  ad minim veniam, quis
nostrud   exercitation  ullamco  laboris
nisi ut aliquip ex ea commodo consequat.
Duis  aute  irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu
fugiat  nulla  pariatur.  Excepteur sint
occaecat cupidatat non proident, sunt in
culpa  qui  officia deserunt mollit anim
id est laborum.
                <-- note the linebreak

```

### Input Details

* You have to write whole executable/interpretable program.
* You may suppose, that the input contains only printable ASCII characters and does not contain tab `\t`.
* The input can contain line breaks. If it does so, they are given as `\n`, `\r`, or `\r\n` depending on what you expect. They are however united throughout whole input.
* The input can be given in STDIN, or as command line arguments. You can use both of them if it suits your needs (for example, read block size from command args and input as stdin). You may not, however, hardcode any part of the input to your program.
* You may suppose that the block size is given as valid positive (`> 0`) number.
* Line break in the input is treated the same way as a space (thus being word separator)
* If the input contains multiple concurrent spaces they are treated as one.

### Output details

* The output has to be formatted into a block of given size. The formatting is done by adding spaces between words.
* The number of spaces between words on a line has to be equal for that line. If it is not possible, additional spaces must be added one by one after words starting from the left.
* If the word is longer that given block size, it will stand alone on a single line (and will exceed the block size).
* If the output should contain only one word, it will be aligned to the left.
* The last line of the output has to be aligned to the left, with only one space between words. The last line of the output has to end with trailing line break.

The answer, with shortest number of bytes after some time, wins.
If you need additional information, leave a comment.

## Test cases

```
Input:
10
Lorem ipsum dolor sit amet,
consectetur adipiscing elit, sed do eiusmod tempor

Output:
Lorem
ipsum
dolor  sit
amet,
consectetur
adipiscing
elit,  sed
do eiusmod
tempor

```

---

```
Input:
20
Lorem     ipsum

dolor  sit amet,

Output:
Lorem   ipsum  dolor
sit amet,

```

---

```
Input:
1
Lorem ipsum dolor sit amet

Output:
Lorem
ipsum
dolor
sit
amet

```

# Answer
> 2 votes
# Pyth, ~~60~~ ~~57~~ ~~54~~ ~~51~~ ~~50~~ 52 bytes

**2015-10-22:** fixing a bug took 2 bytes.

```
=HfTcjd.zdWHAcH]f|qTlH>jd<HhTQ1s.iGcJ|tlG1*d?H-QlsGJ

```

Try it online.

# Answer
> 1 votes
## Ruby, 179 chars

```
n=gets.to_i
s=t=''
$<.read.split.map{|w|if(t+w).size>=n
0while t.size<n&&(1..n).any?{|i|t.sub!(/[^ ]#{' '*i}(?=[^ ])/){|x|x+' '}}
s+=t+?\n
t=w
else
t+=' '+w
t.strip!
end}
puts s,t

```

Way too long...

Semi-ungolfed version:

```
n = gets.to_i
s = t = ''
$<.read.split.map{|w|
    if (t + w).size >= n
        0 while t.size < n && (1..n).any?{|i|t.sub!(/[^ ]#{' '*i}(?=[^ ])/){|x|x+' '}}
        s += t + ?\n
        t = w
    else
        t += ' ' + w
        t.strip!  # this is only necessary because of the very first word >:(
    end
}
puts s,t

```

# Answer
> 0 votes
# CJam, 87 bytes

```
l~:LS*qNSerS%{(2$1$a+_S*,L>{;a\}{\;@;\}?}h;S*a]1>{I1>{LIs,-I,(md1b\aI,(*.+Sf*I.\}I?N}fI

```

This should still be golfable. Try it online in the CJam interpreter.

# Answer
> 0 votes
# Retina, 133 bytes

```
\s+

+`((1)*1 )((?<-2>.)*\S|\S+)
:$3<LF>$1
m+`^(?=.(.)+$[^<TB>]*^(?>(?<-1>1)+)1)((.*):(\S+ +)|(\S+ +)(.*):)
$3$4$5 :$6
+`:|<LF>1+| (?= .*$)
<empty>

```

The `<empty>` represents an empty trailing line. To run the code, put each line in a separate file, replace `<LF>` with linefeed characters (0x0A) and `<TB>` with a tab (0x09). I'll add an explanation when I'm done golfing.

---
Tags: code-golf, typography
---