text:
Find the optimal starting move of Chomp
Chomp is a two-player game with a setup of a rectangle of pieces. Each player takes a turn removing any piece, along with all pieces above it and to its right. Whoever takes the bottom-left piece loses. It can be proven fairly easily that the first player always has a winning move (except with a 1-by-1 rectangle); find it.

Input is the dimensions of the rectangle (two numbers)
Output is the location of the winning move (two numbers)
If there is more than one winning move, then you can output any of them.

This is code golf; shortest code (any language) wins.
Examples
Note: The outputs are just the two numbers; the ASCII art below is just to demonstrate what the numbers mean.
Input: 5 3 (indices 1-based starting from lower-left corner)
Output: 4 3
XXX--
XXXXX
XXXXX

Input: 4 4
Output: 2 2
X---
X---
X---
XXXX

Bonus
Subtract 15 characters from your score if you output all of the winning moves. Each pair of numbers must be separated by a newline.

In your first example, I think that you have one too many dashes

@Kitcar You're right; fixed.

I can't understand the output format. How do those numbers correspond to those positions?

@undergroundmonorail 1-based index from the bottom left. first index is horizontal axis and second index is vertical index.

@Ypnypn This question seems to be good but I can't understand this question! Please explain the question. I have played similar game online here : http://www.transience.com.au/pearl.html

In response to your bounty: In Chess, you have less than 119 possible moves at any given time (usually much less), and no supercomputer to this day has come close to solving Chess using even the best known algorithms. On a 10 by 10 Chomp grid, there are 100 possible first moves, and each of those has 1-99 potential second moves. What makes you think that would be easy to brute force? I recommend limiting your grid size if you want brute force answers. EDIT: But don't do that. Changing requirements mid contest is bad.

@Rusher: There are many moves, but very few states. On a 10x10 board, there are only 184756 possible game states. It's quite simple to brute force that with dynamic programming.

@user2357112 I got 220 possible states for a 10 by 10 board using the formula for a tetrahedral number (440 if you consider that for any state, it could be either player's turn). How did you get 184756?

@Rusher: You must be using a different concept of "state". I used stars and bars; you can show that possible states of a 10x10 game board correspond to ways to put 10 indistinguishable balls in 11 buckets.

@user2357112 I'm sorry, I did 2x2 and 3x3 squares by hand and thought I had a formula. It turns out that I just got lucky and my formula holds for 2 and 3 only. Your formula is correct, and can be seen here: http://mathworld.wolfram.com/StaircaseWalk.html

GolfScript, 82 (108 97 characters - 15 bonus)
~),1/{{:F$0=),{F\+}/}%}@(*(0*\{1${1$\{\(@<},=},{1$\{\(@>},+(-!},:Y!{.,/+0}*;}/;Y{.-1=.@?)' '@)n}/

Since I didn't know for any heuristics this solution performs an exhaustive search over the solution space. You may try the code online. Although the implementation is very efficient the search space grows very fast with increasing input.
Examples:
> 5 3
4 3

> 5 4
3 3

> 6 6
2 2

As mentioned above the implementation does not rely on recursion but visits each node of the search space only once. Below you can find an annotated version of the code which describes the building blocks in more detail.
The representation of a single board of size w * h is given by a list of w numbers in the range 0 to h. Each number gives the amount of pieces in the corresponding column. Thus, a valid configuration is a list where the numbers are non-increasing from start to end (with any move you ensure that all columns to the right are at most as high as the chosen one).
~                   # Evaluate the input (stack is now w h)

# BUILDING THE COMPLETE STATE SPACE
# Iteratively builds the states starting with 1xh board, then 2xh board, ...

),1/                # Generate the array [[0] [1] ... [h]] which is the space for 1xh
{                   # This loop is now ran w-1 times and each run adds all states for the
                    # board with one additional column
  {                 # The {}/] block simply runs for each of the existing states
    :F$0=           #   Take the smallest entry (which has to be the last one)
    ),              #   For the last column all values 0..x are possible
    {F\+}/          #     Append each of these values to the smaller state
  }%
}@(*

# The order ensures that the less occupied boards are first in the list.
# Thus each game runs from the end of the list (where [h h ... h] is) to
# the start (where [0 0 ... 0] is located).

# RUN THROUGH THE SEARCH SPACE
# The search algorithm therefore starts with the empty board and works through all
# possible states by simply looping over this list. It builds a list of those states
# which are known as non-winning states, i.e. those states where a player should
# aim to end after the move

(                   # Skips the empty board (which is a winning configuration)
0*\                 # and makes an empty list out of it (which will be the list of
                    # known non-winning states (initially empty))
{                   # Loop over all possible states
  1$                #   Copy of the list of non-winning states
  {                 #   Filter those which are not reachable from the current state,
                    #   because at least one column has more pieces that the current
                    #   board has
    1$\{\(@<},=
  },
  {                 #   Filter those which are not reachable from the current state,
                    #   because no valid move exists
    1$\{\(@>},+     #     Filter those columns which are different between start and
                    #     end state
    (-!             #     If those columns are all of same height it is possible to move
  },
  :Y                #   Assign the result (list of all non-winning states which are
                    #   reachable from the current configuration within one move)
                    #   to variable Y

  !{                #   If Y is non-empty this one is a winning move, otherwise
                    #   add it to the list
    .,/+
    0               #     Push dummy value
  }*;
}/
;                   # Discard the list (interesting data was saved to variable Y)

# OUTPUT LOOP
# Since the states were ordered the last one was the starting state. The list of
# non-winning states were saved to variable Y each time, thus the winning moves
# from the initial configuration is contained in this variable.

Y{                  # For each item in Y
  .-1=.@?)          #   Get the index (1-based) of the first non-h value
  ' '               #   Append a space
  @)                #   Get the non-h value itself (plus one)
  n                 #   Append a newline
}/

+1 For the solution itself and for the very nicely commented code

Bottom-up dynamic programming, rather than top-down. Nice. I considered doing that, but generating states in a valid order for bottom-up traversal was more work and more confusing than recursive search. I'm surprised the code ended up so long; I expected a terse language like Golfscript could have produced a much shorter solution.

Very nice and well thought out

Python 2 3, 141-15=126
def win(x,y):w([y]*x)
w=lambda b,f=print:not[f(r+1,c+1)for r,p in enumerate(b)for c in range(p)if(r+c)*w(b[:r]+[min(i,c)for i in b[r:]],max)]

Brute-force minimax search. For every possible move, we recursively see if the opponent can win after we make that move. Pretty weakly golfed; someone else should be able to do much better. This feels like a job for APL.

win is the public interface. It takes the dimensions of the board, converts it to a board representation, and passes that to w.
w is the minimax algorithm. It takes a board state, tries all moves, builds a list whose elements correspond to winning moves, and returns True if the list is empty. With the default f=print, building the list has a side effect of printing the winning moves. The function name used to make more sense when it returned a list of winning moves, but then I moved the not in front of the list to save a space.
for r,p in enumerate(b)for c in xrange(p) if(r+c): Iterate over all possible moves. 1 1 is treated as not a legal move, simplifying the base case a bit.
b[:r]+[min(i,c)for i in b[r:]]: Construct the state of the board after the move represented by coordinates r and c.
w(b[:r]+[min(i,c)for i in b[r:]],max): Recurse to see whether the new state is a losing state. max is the shortest function I could find that would take two integer arguments and not complain.
f(r+1,c+1): If f is print, prints the move. Whatever f is, it produces a value to pad the list length.
not [...]: not returns True for empty lists and False for nonempty.

Original Python 2 code, completely ungolfed, including memoization to handle much larger inputs:
def win(x, y):
    for row, column in _win(Board([y]*x)):
        print row+1, column+1

class MemoDict(dict):
    def __init__(self, func):
        self.memofunc = func
    def __missing__(self, key):
        self[key] = retval = self.memofunc(key)
        return retval

def memoize(func):
    return MemoDict(func).__getitem__

def _normalize(state):
    state = tuple(state)
    if 0 in state:
        state = state[:state.index(0)]
    return state

class Board(object):
    def __init__(self, state):
        self.state = _normalize(state)
    def __eq__(self, other):
        if not isinstance(other, Board):
            return NotImplemented
        return self.state == other.state
    def __hash__(self):
        return hash(self.state)
    def after(self, move):
        row, column = move
        newstate = list(self.state)
        for i in xrange(row, len(newstate)):
            newstate[i] = min(newstate[i], column)
        return Board(newstate)
    def moves(self):
        for row, pieces in enumerate(self.state):
            for column in xrange(pieces):
                if (row, column) != (0, 0):
                    yield row, column
    def lost(self):
        return self.state == (1,)

@memoize
def _win(board):
    return [move for move in board.moves() if not _win(board.after(move))]

Demo:
>>> for i in xrange(7, 11):
...     for j in xrange(7, 11):
...         print 'Dimensions: {} by {}'.format(i, j)
...         win(i, j)
...
Dimensions: 7 by 7
2 2
Dimensions: 7 by 8
3 3
Dimensions: 7 by 9
3 4
Dimensions: 7 by 10
2 3
Dimensions: 8 by 7
3 3
Dimensions: 8 by 8
2 2
Dimensions: 8 by 9
6 7
Dimensions: 8 by 10
4 9
5 6
Dimensions: 9 by 7
4 3
Dimensions: 9 by 8
7 6
Dimensions: 9 by 9
2 2
Dimensions: 9 by 10
7 8
9 5
Dimensions: 10 by 7
3 2
Dimensions: 10 by 8
6 5
9 4
Dimensions: 10 by 9
5 9
8 7
Dimensions: 10 by 10
2 2

For the 13x13 take 2x2 and you'd win.

@davidsbro: Yes, that's the winning move for any square board bigger than 1x1, but my code hadn't computed it yet.

Perl 6: 113 108 characters - 15 = 93 points
This one was tough! Here's the uncached version, which is technically correct but will take a very long time for non-trivial inputs.
sub win(*@b){map ->\i,\j{$(i+1,j+1) if @b[i][j]&&!win @b[^i],@b[i..*].map({[.[^j]]})},(^@b X ^@b[0])[1..*]}

It works just like @user2357112's Python implementation (upvote him/her, I couldn't have figured this out without his/her work!) except that win() takes a Chomp board (array) instead of a width and length. It can be used like:
loop {
    my ($y, $x) = get.words;
    .say for @(win [1 xx $x] xx $y)
}

A version with memoization, which can actually handle decent inputs (not optimized for readability, though):
my %cache;
sub win (*@b) {
    %cache{
        join 2, map {($^e[$_]??1!!0 for ^@b[0]).join}, @b
    } //= map ->\i,\j{
        $(i+1,j+1) if @b[i][j] and not win
            @b[^i], @b[i..*].map({[.[^(* min j)]]}).grep: +*;
    },(^@b X ^@b[0])[1..*]
}


text:
Create a memory leak, without any fork bombs
Your task is to create a memory leak. This is a program that uses loads of memory, until the computer runs out and has to do some swapping to save itself from running out. The only way that the memory can be released is by killing the program in the task manager or using a command line kill such as taskkill /im yourprogram /f (in Windows) or even restarting the computer. Merely closing the app should not prevent it from continuing to hog memory.
Rules:

Fork bombs of any sort are banned. That means that infamous Bash line :(){ :|:&};: is banned!
The application must be single-threaded only. This implies the fork bomb rule.
The program must not run other programs. This means that you can't just do something like run(memoryfiller.exe). The only exception to this is programs that are bundled with your OS or language, that are not primarily designed to consume memory (i.e. they have another purpose).  This means that things like cat and ln -s are permitted.
You can take up as much memory as you like. The more the better.
Code must be explained fully.

Good luck. This is a popularity contest so the code with the most votes after 10 days from the asking date wins!

"Closing it should still make it hog memory" - if a program is a shell executable (like most of windows versions of scripting language interpreters are), closing its window will kill the program.

Isn't this just while(1)malloc(999);?

I'm not sure if "Closing it should still make it hog memory" is compatible with "The application must be single threaded only." If no thread has a chunk of memory, the OS can take it back, right?

Does writing an infinite string to a file count?

Just run firefox 26 with a few tabs open running flash for a half hour. It'll bring your computer to its knees.

@mniip. That's the whole point of the challenge. To make a difficult challenge. And doorknob. I wanted something different! ;)

@GeorgeH my previous comment was a troll (I apologize for that) See my answer which hangs computer in 2 second! Once started, your computer will hang so don't try!

"Closing it should still make it hog memory." without spawning some secret processes this is not possible on unices unless you exploit some kernel memory leak or mess directly with the os. You'd need a windows platform (preferably win98 or older) to do that with a conventional code.

Is overriding garbage collection so that nothing happens a valid answer?

@David. Thats fine, Garbage collection can be overridden for this.

Why specifically without fork bombs? Banning one technique is like saying "no Python" or "can't use BeOS". It just seems silly.

You can always install Windows... that'll give you several interesting memory leaks, some of which have been there a really long time. You can also run malloc's, and store into the memory location given to you by malloc, until it barfs up and gives you a 0.L as an error code ("Nil Pointer"), then store into location 0, and see how long the machine lives. Judging by how many "zero-stores" I have seen in many places, Microsoft and Apple run neck and neck with Nil pointer references. grin Dave Small

By "must be single threaded", do you mean "must not explicitly start any threads?" As a comment on the current most popular answer notes, some language runtimes have multiple threads behind the scenes, which effectively excludes those languages from the challenge. Furthermore, @acbabis raises a valid point. I don't know of any languages where "closing the program" wouldn't at least stop the main thread from running. Without at least allowing threads opened in the background by standard libraries (such as GUI threads) or the runtime itself, this seems like an impossible challenge.

@jpmc26. No. I mean you cannot use memory by starting threads so like you cant use for x in range(100000) to spawn loads of threads to take up memory.

How do you define "merely closing the app"? Closing all windows belonging to the process, or must the process itself be terminated? What if the program runs entirely in the background? What's the difference between "closing the app" and "killing the program" then?

@hpsMouse. Closing is pressing the close button (the X in the top right corner). Killing it is going into task manager and clicking end task, or going into processes and ending the process

I wonder if I should remove the 10 days part!!

I'm closing this question as off-topic because it's asking for, in some sense, malicious software, which we do not allow.

Windows
The Win32 API allows you to allocate memory in other processes, and then to read/write that memory remotely. This program has only one thread, which it uses to enumerate each running process on the system, and then repeatedly allocate 1MB buffers in each process until the allocation fails. When it finishes with one process, it moves on to the next. The allocations are not released when the calling program finishes - only when/if each target process finishes. This hangs a 2GB Windows 7 VM in about 10 seconds. It does require running as admin.
To compile: cl /MD leak.cpp /link psapi.lib
#include <windows.h>
#include <psapi.h>

typedef void (*ProcFunc)(DWORD pid);
#define ALLOC_SIZE 0x100000
LPVOID buf;

void ForEachProcess(ProcFunc f)
{
    DWORD aProcesses[1024], cbNeeded;

    if (!EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded))
        return;

    for (unsigned int i = 0; i < cbNeeded / sizeof(DWORD); i++)
        if (aProcesses[i] != 0)
            f(aProcesses[i]);
}

void RemoteLeak(DWORD pid)
{
    HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pid );
    if (hProcess == NULL)
        return;

    for (;;)
    {
        LPVOID ptr = VirtualAllocEx(hProcess, NULL, ALLOC_SIZE,
                                    MEM_COMMIT, PAGE_READWRITE);
        if (ptr == NULL)
            return;

        WriteProcessMemory(hProcess, ptr, buf, ALLOC_SIZE, NULL);
    }
}

int main(void)
{
    buf = malloc(ALLOC_SIZE);
    if (buf == NULL)
        return 0;

    memset(buf, 0xFF, ALLOC_SIZE);

    ForEachProcess(RemoteLeak);

    return 0;
}

Windows is evil.

I need to shut down tonight. Ill give this a go ;)

" (running as a normal user, not using admin privileges" - not sure about this, you need SeDebugPrivilege which by default is not present in regular user's token

@rkosegi Thanks, fixed.

+1 This deserves many upvotes as it so far is the only answer that meets the original Closing it should still make it hog memory requirement. Very creative solution :-)

@rkosegi: Sure about SeDebugPrivilege? AFAIR (my Win32 times are a while ago) you do not need it for own processes, and there surely are a few around.

Hi @Daniel, according to http://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx and also my little experience, I needed to adjust token (even if I was admin on WinXP) to make it work.My program was simply opening specific processes, enumerated it's threads and kill them.Maybe I wrong here, that's why I said "I'm not sure", but MSDN said so.BTW Andrew is accessing not just own thread in his answer.

@rkosegi: "opening specific processes" is the key here. What processes? If they have been create with the same token than leak.exe, their DACL should grant you access. Basically, everything you could (as a non-Admin) kill from TaskManager should also be leakable by this nice prog. (SeDebugPrivilege is the one that, if enabled, bypasses any process DACL, so you can also access foreign processes.)

Is the WriteProcessMemory() really necessary? In theory, MEM_COMMIT of VirtualAllocEx() should be enough. Also, you probably do not need PROCESS_ALL_ACCESS, but only PROCESS_VM_OPERATION.

@Daniel you're right that it's the only solution that still hogs memory when it gets killed. But the requirements state that it's fine if the memory is released when the program is killed. Therefore my solution also fullfils that requirement, by disabling any way to normally terminate the program. Killing it is the only way to stop it from running. But Andrew Medico definitly has a special way to keep the memory leaked after termination. That's really a nice one ;)

The RAM Disk and shared memory based approaches also still hog memory after being killed. This solution does deserve plentiful upvotes for the shear perverseness of allocating memory in other processes, though.

Congratulations! You have won the contest :)

Java
import java.util.concurrent.atomic.AtomicInteger;

public class Hydra {
  // Not actually necessary for the leak - keeps track of how many Hydras there are, so we know when they're all gone
  public static AtomicInteger count = new AtomicInteger(0);
  public Hydra() {
    count.incrementAndGet();
  }
  protected void finalize() {
    new Hydra();
    new Hydra();
    count.decrementAndGet();
  }

  public static void main(String[] args) throws InterruptedException {
    new Hydra();
    while (Hydra.count.get() > 0) {
      // Prevent leaks ;-)
      System.gc();
      System.runFinalization();
    }
  }
}

Explanation
You might assume that since there are no references in the code (other than count, which you can safely ignore), it can't leak. However, the finalizer creates two new Hydras, and whilst it doesn't hold references for these either, they'll hang around until finalized. This means that the program only leaks memory during garbage collection - hence the calls to System.gc() and System.runFinalization().

@TimS. where's your god now?!?

Are System.gc() and System.runFinalization() necessary? That is will the gc randomly run sometimes, or do you have to either fill some memory, or call gc?

In a typical program, System.gc() and System.runFinalization() wouldn't be necessary. Garbage collection would happen naturally due to memory pressure. However in this application there's no memory pressure until garbage collection starts running. I thought about artificially introducing some (for example, by moving new Hydra() inside the loop), but figured this was more evil.

The application can simply be terminated so the operating system can recover the memory you acquired. The problem is that the finalize method is only invoked when an object is garbage collected, but no garbage collection is performed on shutdown, allowing to break your finalization loop... Additionally your code breaks rule #2, because invoking System.runFinalization() spawns a secondary finalization thread in addition to the primary one that is always created by the virtual machine.

Yeah, I didn't pay much attention to "Closing it should still make it hog memory" caveat, as it didn't seem meaningful (apart from neat OS hacks like @german_guy's). Java always spins up a finalization thread, so perhaps there's no way for a Java application to obey rule #2.

I also think that rule #2 is a grey zone in this case and the more I think about it, it's okay... But can't you also block any terminating signals in Java? If you do that, your code would satisfy the rules and requirements and you'd have a nice solution to the given problem.

AFAIK, blocking terminating signals is a bit of a black art, especially if you want to do it portably. I figured other answers would have interesting ideas on blocking termination, and I'd just post an evil way to leak memory.

On Unix systems, you cannot block SIGKILL (signal 9), so you cannot make your program unstoppable (well, except if you manage to get it into a state of uninterruptible wait ... so maybe remote-killing an NFS server whose files you access might work ;-))

Wow.  I was going to complain about the use of System.gc() until you pointed out the Finalizer block.  Clever!
+1 for demonstrating why Java programmers still need to worry about memory!

@celtschk it's okay that you can't block SIGKILL. According to the task, it's the only legit way to give the memory back to the operating system.

Hello. Sorry about this, but one of the rules of the program says it still has to hog memory when it is closed. Therefore sadly, even though you have the most upvotes, I am going to have to give the answer to the second placed answer. I am really sorry :(

No worries. I knew I was bending the rules, and I was surprised to get as many upvotes as I did. The winning entry is suitably evil. I was a bit disappointed that @german_guy withdrew his entry - it was my personal favorite.

C
Using the C programming language and tested with Linux kernel 2.6.32-49-generic and libc-2.11.1.so.

The only way that the memory can be released is by killing the program in task manager or using taskkill /im yourprogram /f or even restarting the PC.

This is achieved by blocking any signals except for SIGKILL and SIGSTOP.

Closing it should still make it hog memory.

This actually confused me... Killing or closing it both results in termination of the process, allowing the operating system to claim back any memory that was allocated by the process. But then i got to think that by closing it you might mean to close the terminal or any other parent process that executes the memory leaking process. If i got that right, then i solved this problem by blocking any signals, which turns the process into a daemon when the parent process is terminated. That way you can close the terminal the process is running in and it will continue running and proceed to leak memory.

Fork bombs of any sort are banned. That means that infamous bash :(){ :|:&};: is banned!

The process does not fork.

The application must be single threaded only. This implies the fork bomb rule

No new threads are spawned.

The program must not run other program. This means that you cant just do something like run(memoryfiller.exe)

No new processes are spawned.

You can take up as much memory as you like. The more the better.

As much as the operating system can provide.

Code must be explained fully.

Added comments to the source.
And finally here's the code:
#define _GNU_SOURCE

#include <stdio.h>
#include <signal.h>
#include <sys/resource.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {

    /*
    set the real, effective and set user id to root,
    so that the process can adjust possible limits.
    if the process doesn't have the CAP_SETUID capability, terminate the process.
    */
    if (setresuid(0, 0, 0) == -1) {
        printf("Are you root?!\n");
        return 1;
    }

    /*
    block all signals except for kill and stop.
    this allows to terminate the parent process (most likely a terminal)
    that this process is running in and turn it into a daemon.
    additionally this makes it impossible to terminate the process
    in a normal way and therefore satisfies the requirement that closing
    it should still make it hog memory.
    */
    sigset_t mask;
    sigfillset(&mask);
    sigprocmask(SIG_SETMASK, &mask, NULL);

    /*
    allow the process to acquire a virtually unlimited amount of memory
    and queue a virtually unlimited amount of signals.
    this is to prevent an out of memory error due to a virtual limit for the root user,
    which would prevent the process from leaking any more memory
    and to prevent the process from getting killed due to too many queued
    signals that the process is blocking.
    */
    struct rlimit memory = { RLIM_INFINITY, RLIM_INFINITY },
                  signal = { RLIM_INFINITY, RLIM_INFINITY};
    setrlimit(RLIMIT_AS, &memory);
    setrlimit(RLIMIT_SIGPENDING, &signal);

    /*
    allocate a buffer big enough to store a file name into it
    that is generated from the process' pid.
    if the file can be opened (which should always be the case unless /proc is not mounted)
    the file will be opened and the string -17 followed by a new line written to it.
    this will cause the oom killer to ignore our process and only kill other,
    innocent processes when running out of memory.
    */
    char file_name[20];
    sprintf(file_name, "/proc/%u/oom_adj", getpid());

    FILE* oom_killer_file = fopen(file_name, "w");
    if (oom_killer_file) {
        fprintf(oom_killer_file, "-17\n");
        fclose(oom_killer_file);
    }

    /*
    get the size of virtual memory pages in bytes,
    so the process knows the size of chunks that have to be
    made dirty to force the kernel to map the virtual memory page into RAM.
    */
    long page_size = sysconf(_SC_PAGESIZE);

    // allocate a virtually infinite amount of memory by chunks of a page size.
    while(1) {
        // will overwrite any previous stored address in tmp, leaking that memory.
        char* tmp = (char*) malloc(page_size);
        if (tmp)
            // make the memory page dirty to force the kernel to map it into RAM.
            tmp[0] = 0;
    }

    return 0;
}

For anyone who's interested in what happens if you keep this program running: On my test system with 2GB RAM and 4GB swap space it took about 10 minutes to fill up the RAM and swap. The OOM killer started its work and three minutes later kind of all processes have been killed. Even mouse, keyboard and display have been dropped by the system. /var/log/kern.log shows no useful information, except for the processes that have been killed.

I edited the source to make the oom killer ignore the process and kill innocent processes to free memory instead.

For anyone who's interested in what happens if you keep this program running: On my test system with 2GB RAM and 4GB swap space it took about 10 minutes to fill up the RAM and swap. The OOM killer started its work and three minutes later kind of all processes have been killed. Even mouse, keyboard and display have been dropped by the system. /var/log/kern.log shows no useful information, except for the processes that have been killed.

Haha, that's wonderful! You should edit that description into your answer. +1

Would be nice if the one who downvoted would leave a comment why, so I have a chance to improve my answer.

I didn't downvote, but it would be nice if the code could be formatted so no horizontal scrolling is necessary to read the comments.

To allocate your memory faster, grab it with mmap instead of malloc.

+1 for 1) causing processes handing input/output devices to be killed and 2) creating a program that's hard to track from the logs. This is mustache-curling levels of evil.

Pure Bash
Not a fork-bomb, I promise:
:(){ : $@$@;};: :

It looks a lot like a fork bomb, and uses a similar recursive technique, but no forks.  Of course this will run your shell right out of memory, so you are advised to start a new shell before pasting this command.

Define a function called :
The function simply recursively calls itself with $@ (arg list) doubled
After the function definition, the : function is called with an initial arg :

Output:
$ bash
$ :(){ : $1$1;};: :
bash: xmalloc: ../bash/stringlib.c:135: cannot allocate 536870913 bytes (5368795136 bytes allocated)
$

In a previous edit of this answer I did a=$(yes), but I noticed the rule "The program must not run other program", so I need to use pure bash instead without calling any coreutils or anything else.

Here's another one:
PLEASE DON'T RUN THIS ON A PRODUCTION MACHINE
:(){ : <(:);};:

Again, this is not a fork bomb - everything is run from within one thread.  This one seems to quite handily bring my Ubuntu VM to its knees, with little room for recovery, other than reboot.
As in the classic fork bomb, a recursive function :() is defined.  However it does not fork out calls to itself.  Instead it calls itself with one argument, which is itself called in a process substitution.  Because process substitution works by opening an file descriptor /dev/fd/n, this not only eats up process (bash) memory, it will also eat up some kernel memory too.  On my Ubuntu machine this has the effect of making the window manager inoperable after a few seconds, then shortly after ending up with this screen:

Clicking OK then gives this screen:

None of these options seem to be much help - at this point restarting seems to be the only good option.

$ which yes -> /usr/bin/yes

"The only way that the memory can be released is by killing the program in task manager or using taskkill /im yourprogram /f or even restarting the PC. Closing it should still make it hog memory." >> The bash can be terminated using a SIGTERM, so killing it is not required to make it stop running. Also it stops running when the system runs out of memory. Once the bash terminated, either by SIGTERM or by running out of memory, the memory is given back to the operating system.

This doesn't work for me... sort of... I can see the memory gradually going away, but this happens very slowly, and it also can be killed by just pressing ctrl+c. It's running now for 1 minute and it's occupied about 1GB. I have a VERY fast machine... but that shouldn't matter, right?

Replying to my own comment: The command actually killed the bash after about 2mins 49sec. I originally assumed it's going to instant based on this answer.

@StefanosKalantzis Thanks for your comments.  It made me think a bit more and I just found an even more evil shell snippet - see edit.

XML
<!DOCTYPE boom [
<!ENTITY Z 'ka-boom!'><!ENTITY Y '&Z;&Z;'><!ENTITY X '&Y;&Y;'><!ENTITY W '&X;&X;'>
<!ENTITY V '&W;&W;'><!ENTITY U '&V;&V;'><!ENTITY T '&U;&U;'><!ENTITY S '&T;&T;'>
<!ENTITY R '&S;&S;'><!ENTITY Q '&R;&R;'><!ENTITY P '&Q;&Q;'><!ENTITY O '&P;&P;'>
<!ENTITY N '&O;&O;'><!ENTITY M '&N;&N;'><!ENTITY L '&M;&M;'><!ENTITY K '&L;&L;'>
<!ENTITY J '&K;&K;'><!ENTITY I '&J;&J;'><!ENTITY H '&I;&I;'><!ENTITY G '&H;&H;'>
<!ENTITY F '&G;&G;'><!ENTITY E '&F;&F;'><!ENTITY D '&E;&E;'><!ENTITY C '&D;&D;'>
<!ENTITY B '&C;&C;'><!ENTITY A '&B;&B;'><!ENTITY z '&A;&A;'><!ENTITY y '&z;&z;'>
<!ENTITY x '&y;&y;'><!ENTITY w '&x;&x;'><!ENTITY v '&w;&w;'><!ENTITY u '&v;&v;'>
<!ENTITY t '&u;&u;'><!ENTITY s '&t;&t;'><!ENTITY r '&s;&s;'><!ENTITY q '&r;&r;'>
<!ENTITY p '&q;&q;'><!ENTITY o '&p;&p;'><!ENTITY n '&o;&o;'><!ENTITY m '&n;&n;'>
<!ENTITY l '&m;&m;'><!ENTITY k '&l;&l;'><!ENTITY j '&k;&k;'><!ENTITY i '&j;&j;'>
<!ENTITY h '&i;&i;'><!ENTITY g '&h;&h;'><!ENTITY f '&g;&g;'><!ENTITY e '&f;&f;'>
<!ENTITY d '&e;&e;'><!ENTITY c '&d;&d;'><!ENTITY b '&c;&c;'><!ENTITY a '&b;&b;'>
]>
<boom a="&a;"/>

Then pass the document to an XML parser that doesn't do entity reference loop/recursion detection.  For example, xpath included with perl:
xpath boom.xml /

How it works:

The parser encounters <boom a="&a;">
The parser expands "&a;" into "&b;&b;"
The parser expands one of the "&b;" into "&c;&c;" (on return, it will expand the other "&b;")
The parser expands one of the "&c;" etc...

If full expansion could occur, there would be 2^52 expansion of "ka-boom!".  Assuming 2-bytes per character, it will try to use 64 PiB.  The expansion goes "ka-boom!" at a time, so you can usually watch it use up all memory in top.
This goes by various names, good overview here: http://projects.webappsec.org/w/page/13247002/XML%20Entity%20Expansion

Essentially a copy of Billion laughs

@ColeJohnson Yup that's it!  I contributed to the WASC Threat Classification project, so I felt obligated to point to WASC rather than Wikipedia. :)

C++
int main()
{
    for(;;)int *a=new int;
}

This code was unexpected! It hung my computer while the task manager was open and showed that it took 890 Mb of memory in 1 second then it also hung. I don't know how this works, maybe it keeps on giving memory to a variable.To explore more of this code I added a statement delete a; and every thing was fine while testing (no hanging) So, I think that the chunk of memory is given (due to new int) and then taken back (due to delete a) to the free space in the new code below.
int main()
{
    for(;;)
    {
         int *a=new int;
         delete a;
    }
}

So, I conclude that NO RAM IN THIS WORLD CAN HANDLE THIS CODE!!!
EDIT : But many processors can for e.g. intel core 2 duo can't handle this code but
intel core i-series can (worked for me...)
Remember the answer to the question is the 1st code , second one is for explanation.

Nice, the compiler thinks you are still going to use the new int even though you overwrote the pointer, so you can never access it again...So no garbage collection is called and you fill up memory faster than a fat kid eats skittles

@DavidWilkins: ...this is C++, C++ has no garbage collector.

@Phoshi thanks for correcting me...C++ leaves that up to you

Haha this solution is the first one that came to mind when I read the question.

If it's unexpected to you that this code leaks, then I think you shouldn't use C++ until you learn it better.

@svick But its not also like hitting dart-board in dark! I had some Idea that this will do the job question wants.

@svick How the hell is he supposed to 'learn it better' if he 'shouldn't use C++'?

@Kevin I meant not use it in production or post code as answers on Q&A sites. Of course writing throw-away code to learn is okay at any level.

He should use a modern language, if you want no GC and static types but nice modern bells and whistles try rust

@a_programmer well, if you want bugs in your code you have to switch to older versions!

There is nothing unexpected in the first code. An object may do any stuff it wants, for example adding itself to a list in another translation unit; or even cleaning up itself. The compiler cannot make guesses about how unused an object actually is. This is important in some situations, for example wrt scoped-locking in multithreading.

BrainFuck
+[>+]

Explanation:
To enter the loop it increases the cell to 1. It moves to the next cell increasing that to 1 as long as the last cell was positive.
Usually A BrainFuck interpreter is flawed with having a hard limit to the number of cells on the tape, but some interpreters adds cells dynamically. These will continue to consume memory until it's no more to consume.
beef is one such interpreter and it's available in the Ubuntu Software Center and  my current run on an unused machine started 29 hours ago and has consumed 1GB of RAM in that time. Here's the the output of top
PID  USER        PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND
2978 sylwester   20   0 1030m 984m 2536 R 100,1 12,4   1750:52 beef

It has 4GB of cache and 6GB of swap so I guess I'll update this answer with how it went in about 12 days.
UPDATE 03.24 17:11
PID  USER        PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND
2978 sylwester   20   0 1868m 1,8g 2456 R  99,9 22,9   6008:18 beef

UPDATE 03.31 00:20
PID  USER        PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND
2978 sylwester   20   0 2924m 2,8g 2052 R 100,0 36,1  15019:46 beef

So it's been running for 10 days. Seems like it will be running for at least 10 more before something interesting happens.

Nice and short.

C and POSIX
Here I am aiming for a highly portable solution. The problem is that pure C doesn't seem to have a way of telling the Operating System that the memory should remain allocated after the program closes. So I allow myself to use POSIX; most OS's have some claim to POSIX compatibility including Windows, Linux and MacOS X. However, I have only tested it on Ubuntu 12.04 32bit. It does not require superuser permissions.
This solution is essentially the traditional while(1){malloc(1);} solution. However instead of malloc, it uses the POSIX shared memory functions. Since it assigns a shared memory identifier to each allocation, it is still possible to access the memory once the process terminates. Thus the kernel cannot free the memory.
#include <sys/types.h>
#include <sys/shm.h>
#include <string.h>

#define SHMSZ (2*1024*1024) /*Ubuntu rejects shared allocations larger than about 2MiB*/

main() {
  int shmid;
  key_t key = 0xF111; /* Lets use `Fill' as our first ID.*/
  char *shm;

  while(1) { /* Like malloc, but using shared memory */
    if ((shmid = shmget(key, SHMSZ, IPC_CREAT|0666)) < 0){return 1;}/*Get shared memory*/
    if ((shm = shmat(shmid, NULL, 0)) == (void *) -1) { return 1; } /*Attach it        */
    memset(shm,0,SHMSZ);                                            /*Fill it up       */
    key++                                                           /*On to the next ID*/
  }
}

Best and most brilliant C answer IMO. +1

Nice one. The first solution i came up with was Andrew Medico's, but as that isn't possible on Linux and as I don't like Windows programming, I wanted to leak through shared memory, but couldn't remember the POSIX function names. Thanks for remembering me of them ;) All I found was only mmap stuff that is unmapped on process termination...

C#
Forgetting to unsubscribe from events before the handler goes out of scope will cause .NET to leak memory until it throws OutOfMemoryException.
using System;

class A
{
    public event Action Event;
}

class B
{
    public void Handler() { }
}

class Program
{
    static void Main()
    {
        A a = new A();

        while( true )
            a.Event += new B().Handler;
    }
}

Explanation: Inside the while loop, we construct a new object, causing the framework to allocate more memory, but we also prevent the new instance of B from being released when it goes out of scope by assigning an instance method to an event in a different class, the result being that the new instance of B becomes unreachable from our code, but a reference still exists, meaning the GC won't release it until a also goes out of scope.
Static events have the same pitfall, since they never go out of scope, they're only cleaned up when the process terminates, unless you unsubscribe from the event first. Always store your references, people!
using System;

class Program
{
    static event Action Event;

    static void Main()
    {
        while( true )
            Event += new Action( delegate{ } );
    }
}

The above works on the same idea, the handler becomes unreachable once the while loop goes out of scope, making it impossible to unsubscribe from the event, meaning the memory will sit there until the program terminates. Static events are arguably more dangerous than instance events, because you can ensure they never go out of scope.
EDIT: You can also do the same with basically any other object as well, just as long as you add a reference while at the same time ensuring there's no way to free that reference.
Here's an example that uses static objects and arrays.
using System;
using System.Collections.Generic;

static class Leak
{
    private static List<decimal[]> Junk;

    static Leak()
    {
        Junk = new List<decimal[]>();
    }

    public static void Add( uint size )
    {
        decimal[] arr = new decimal[size];
        Junk.Add( arr );
    }
}

class Program
{
    static void Main()
    {
        while( true )
            Leak.Add( 1 );
    }
}

Arrays keep being added to the list, but there's no way to clear the list without modifying the code, which would be impossible for closed-source applications. Increasing the number passed to Leak.Add will cause it to leak faster, if you set it high enough it will just result in an immediate OverflowException being thrown.

bash (no external utilities)
No fork bomb here.
Warning: It might kill your shell.
Just trying to create an array of integers for reference because I keep forgetting how integers look like.
while :; do _+=( $((++__)) ); done

Results in:
xmalloc: expr.c:264: cannot allocate 88 bytes (268384240 bytes allocated)

+1 for "because I keep forgetting how integers look like" :)

J (7)
WARNING: This froze my system when I tried it (Windows 8, J 8.01, in the qt terminal).
2#^:_[_

2# doubles the length of the argument by duplicating each element,
^:_ finds the fixpoint of the given function (but there isn't one so it loops endlessly),
[_ calls it with _ as the argument.

Haskell (Graham's number)
It's very simple: this calculates the Graham's number
Unlike other examples here, it won't run forever... it will use a lot of cpu, but theoretically it could terminate. if it weren't for the fact that to store the number...

the observable universe is far too small to contain an ordinary digital representation of Graham's number, assuming that each digit occupies one Planck volume.

(according to wikipedia)
import Data.Sequence
import Data.Foldable

(↑) a 1 b = a ^ b
(↑) a _ 0 = 1
(↑) a i b = a ↑ (i-1) $ a ↑ i $ b-1

graham = last $ toList $ iterateN 64 (\i -> 3 ↑ i $ 3) 4
main = print graham

So, the idea is that the memory will be used by a (series of increasingly) enormous Integer(s) (Haskell's Integers are of arbitrary size).
If you want to test it out, you might have to increase the stack size or load it inside ghci.

Dumb universe, not conforming to the Haskell standard for Integers. Why can't it support arbitrary size?

Inspired by @comintern.
Replacing /dev/null. Engaging sneaky mode. Requires kernel headers, superuser mode and a working compiler.
# make
# rm /dev/null
# insmod devnull.ko
# chmod go+rw /dev/null

Have fun.
Makefile:
MODULE := devnull
KVERS  ?= $(shell uname -r)
KDIR   ?= /lib/modules/$(KVERS)/build
KMAKE := make -C $(KDIR) M=$(PWD)

obj-m += $(MODULE).o

all:
    $(KMAKE) modules

install:
    $(KMAKE) modules_install

clean:
    $(KMAKE) clean

Source code:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/version.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/uaccess.h>

#define DEVICE_NAME "null"
#define MAJOR_NUMBER 0

MODULE_LICENSE("GPL");
MODULE_AUTHOR("nola <florian@n0la.org>");
MODULE_DESCRIPTION("/dev/null - memory leak style");
MODULE_VERSION("0.1");
MODULE_SUPPORTED_DEVICE("null");

static struct class *class_null;
static int major = 0;

static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char *, size_t, loff_t *);
static loff_t device_llseek(struct file *, loff_t, int);

static struct file_operations fops = {
    .owner = THIS_MODULE,
    .llseek = &device_llseek,
    .read = &device_read,
    .write = &device_write,
    .open = &device_open,
    .release = &device_release
};

static int __init mod_init(void)
{
    struct device *dev_null;

    if ((major = register_chrdev(MAJOR_NUMBER, DEVICE_NAME, &fops)) < 0) {
        return major;
    }

    /* create /dev/null
     * We use udev to make the file.
     */
    class_null = class_create(THIS_MODULE, DEVICE_NAME);
    if (IS_ERR(class_null)) {
        unregister_chrdev(major, DEVICE_NAME);
        return -EIO;
    }

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
    dev_null = device_create(class_null, NULL, MKDEV(major, 0),
                             NULL, "%s", DEVICE_NAME
        );
#else
    dev_null = device_create(class_null, NULL, MKDEV(major, 0),
                             "%s", DEVICE_NAME
        );
#endif
    if (IS_ERR(dev_null)) {
        class_destroy(class_null);
        unregister_chrdev(major, DEVICE_NAME);
        return -EIO;
    }

    return 0;
}

static void __exit mod_exit(void)
{
    device_destroy(class_null, MKDEV(major, 0));
    class_unregister(class_null);
    class_destroy(class_null);
    unregister_chrdev(major, DEVICE_NAME);
}

static int device_open(struct inode *inode, struct file *file)
{
    file->f_pos = 0x00;

    try_module_get(THIS_MODULE);
    return 0;
}

static int device_release(struct inode *inode, struct file *file)
{
    /* decrement usage count: Not. Uncomment the line for less fun. */
    /* module_put(THIS_MODULE); */
    return 0;
}

static loff_t device_llseek(struct file *filep, loff_t offs, int mode)
{
    loff_t newpos;

    switch (mode) {
    case 2:
    case 0:
        newpos = offs;
        break;

    case 1:
        newpos = filep->f_pos + offs;
        break;

    default:
        return -EINVAL;
    }

    if (newpos < 0) {
        return -EINVAL;
    }

    filep->f_pos = newpos;

    return newpos;
}

static ssize_t device_read(struct file *filep, char *dst, size_t len,
                           loff_t *off)
{
    char *buf = NULL;

    if (dst == NULL || len == 0) {
        return -EINVAL;
    }

    buf = kmalloc(sizeof(char) * len, GFP_KERNEL);
    if (buf == NULL) {
        return -EINVAL;
    }

    /* Do how a /dev/null does.
     */
    memset(dst, 0, len);

    *off += len;
    return len;
}

static ssize_t device_write(struct file *filep, const char *src, size_t len,
                            loff_t *off)
{
    char *buf = NULL;

    buf = kmalloc(sizeof(char) * len, GFP_KERNEL);
    if (buf == NULL) {
        return -EINVAL;
    }

    *off += len;
    return len;
}

module_init(mod_init);
module_exit(mod_exit);

Warning this may force you to reboot!
To remove it:
# rmmod -f devnull # or a reboot
# rm -rf /dev/null
# mknod /dev/null c 1 3
# chmod go+rw /dev/null

Ruby
Everyone knows that sum(1/n^2) = pi^2/6
So I can define an approximation function:
pi_approx = lambda {|i|
Math.sqrt(
  6*(
    (1...Float::INFINITY).map{|n| n.to_f**(-2)}.take(i).reduce(:+)
    )
  )
}

p pi_approx.(100_000)

Of course the (1..infinity) will run wild.
Notice however that using lazy would make this work ;)
pi_approx = lambda {|i|
Math.sqrt(
  6*(
    (1...Float::INFINITY).lazy.map{|n| n.to_f**(-2)}.take(i).reduce(:+)
    )
  )
}

p pi_approx.(100_000)
#=> 3.141583104326456

C - 28 25 characters (full program)
Don't run that one, or your system will quickly get frozen!
main(){while(malloc(9));}

The call to malloc will reserve 9 bytes of memory and request new memory pages from the operating system regularly.
The memory allocated by malloc is immediately leaked as no pointer to the returned address is stored.
Once the system has run out of memory (RAM and swap space) or the memory limit for the process is reached, the program will break out of the while-loop and terminate.

Not for long - any reasonably modern system should have an OOM killer that kicks in and kills the process.  At least Ubuntu 12.04 does.

Well, I crashed my Ubuntu 13.10 while trying this code...

@DigitalTrauma Does e.g. FreeBSD have an OOMK?

main(){while(malloc(9));} saves another 3 characters, and fills my memory pretty much instantaneously.

@gmatht: thanks for the suggestion! I edited the answer... though I liked the idea of increasing the size of the block on every loop.

Yes & tmpfs
Why write a new program when one comes for free with Ubuntu?
yes > /run/user/$UID/large_file_on_my_ramdisk

As you probably know, or have already guessed, Ubuntu mounts /run/user/ by default as a tmpfs which is a type of RAM disk.
You don't even have to close it. It will politely close itself, leaving a nice chunk of memory allocated. I presume yes is a single-threaded, single-process program that does not call any other (writing to an existing RAM disk is also trivially portable to the language of your choice).
It has a minor bug: Ubuntu limits the user writable tmpfs /run/1000 to 100 MB by default, so the swap death feature may not be supported on your machine out-of-the-box. However I managed to fix this on my machine with the following quick workaround:
sudo mount -o remount,size=10G tmpfs /run/user/

I don't have a /run/user directory at all. What version of Ubuntu do you use and what did you install for this?

Ubuntu Trusty Tahr (14.04). No special install needed.

To find whether you have any tmpfs filesystems mounted, you can list them with df -t tmpfs.  My Ubuntu system has a lovely large /run/shm available...

VBScript
do
    Set d1 = createobject("Scripting.Dictionary")
    d1.add true, d1
    Set d1 = Nothing
loop

We are creating a dicionary that point to itself. Then we think that we destroy the dictionary by setting it to Nothing. However, the dictionary still exists in memory because it has a valid (circular) reference.
The loop, but also the memory hog, causes the program to hang. After shutdown of the program, the memory is still in use. The system can only be restored by restarting it.

Uh, really? VBScript doesn't just use VB.NET under the hood? Circular references aren't normally problems for garbage collectors, except for simple reference count implementations, and termination of the program should result in releasing its entire heap, no?

@DavidConrad You would thinks so, but I had to restart my machine every time I investigated this and run this type of scripts.

VBScript predates VB.Net significantly - it isn't a command line version of VB.Net; it's an interpreted subset of legacy Visual Basic.

Thanks, both of you. I didn't realize what the relationship was between VBScript and VB.NET.

Bash
Warning: The following code will make your computer unbootable.
printf "\\xe8\\xfd\\xff" | dd of=/dev/sda
reboot

Warning: The preceding code will make your computer unbootable.
Replace /dev/sda with your boot drive. This writes E8 FD FF to the beggining of your boot sector. When booting, the BIOS reads your boot sector into memory and executes it. Those opcodes are equivalent to this assembly:
label:
  call label

This is infinite recursion, which will eventually cause a stack overflow.

In your Assembly example, you could save a character(assuming the name "label" is necessary) by using jmp rather than call

call leaves the return address on the stack for ret.  jump wouldn't cause a stack overflow.

Haskell
main=print $ sum [0..]

This tries to add up the counting numbers. Haskell does evaluate the partial sums, it just becomes an infinite addition statement. If you run the compiler with optimization flags, it may not work though.

Bash
Since we can use utilities that aren't specifically designed to consume memory, I focus on a utility to free memory: swapon. This is used to allow the kernel to free up memory by writing to disk.
This script performs two optimizations: (1) Mounting tmp as tmpfs (a type of RAM disk) to make /tmp faster and (2) creating a swapfile to free up memory. Each of these are reasonable by themselves but if a careless user does both then it sets up an cycle of swapping: when the OS tries to swap out pages, it writes to the tmpfs; this makes the tmpfs use more memory; this increases the memory pressure causing more pages to be swapped out. This can take a few minutes on my VM, plenty of time for you to watch the system dig itself into a hole using top.
Closing the program makes little difference since the program itself allocates hardly any memory. Indeed it is not trivial to free memory since you can't free memory by unmounting the tmpfs before you swapoff the swapfile, and that is hard to do until you have freed memory.
This answer could be considered an cautionary tale against blinding applying cool tricks from the net without understanding them.
sudo mount -t tmpfs -o size=9999G tmpfs /tmp # Use tmpfs to make /tmp faster
truncate -s 4096G /tmp/swap                  # Now make a giant swap file to free up memory
sudo losetup /dev/loop4 /tmp/swap            # Use a loopback so we can mount the sparse file
sudo mkswap /dev/loop4
sudo swapon /dev/loop4
#The following line would cause a quick swap death, but isn't needed.
#dd if=/dev/zero of=/tmp/zero bs=1          # Zero the tmp dir so the VM can free more memory

ECMAScript 6:
z=z=>{while(1)z()};_=i=>(i+=1,i-=1,i++,i--,--i,++i,i<<=2,i>>=2,i+=0|Math.round(1+Math.random())&1|0,z(x=>setInterval(x=>z(x=>new Worker('data:text/javascript,'+_.toSource()),5))));setInterval(x=>z(x=>_(...Array(9e3).map((x,z)=>z*3/2*2/4*4e2>>2<<2))),5)

Ungolfed:
function forever(code) {
    // Loop forever
    var counter = 0;

    while (counter++ < 10) setInterval(code, 5);
};

function main(counter) {
    // Do some work.
    counter += 1; counter -= 1;

    counter++; counter--;
    --counter; ++counter;

    counter <<= 2;
    counter >>= 2;

    counter += 0 | Math.round(1 + Math.random()) & 1 | 0;

    forever(() => {
        setInterval(() => {
            forever(() => new Worker('data:text/javascript,' + main.toString()));
        }, 5);
    });
};

setInterval(() => {
    forever(() => {
        main(...Array(9e3).map((currentValue, index) => index * 3 / 2 * 2 / 4 * 4e2 >> 2 << 2));
    });
}, 5);

Note: It uses setTimeout, which is defined as part of Timers - the HTML Living Standard.
Try it on Mozilla Firefox (you could paste it in the developer console). Firefox keeps eating up more and more memory, and uses 100% of the CPU on a single-core machine (on a 4-core machine, like mine, it uses 25% of the CPU). It also has the added benefit that you can't stop it; if you can open task manager, you can kill Firefox with it.

It uses 100% of a core. On your quadcore processor, that results in 25% of CPU usage.

@Electrosa Yes, you're absolutely correct. I've updated my answer.

This is not a code golf question, please try to make your code readable.

@PaŭloEbermann OK. I've posted an ungolfed version.

PHP (linux only):
This code is untested, since that I don't have a linux computer with php running.
But this is my proof of concept:
ignore_user_abort(true);
ini_set('memory_limit',-1);
ini_set('max_execution_time',0);
/*
    sets php to ignore if the script was canceled in the browser
    (like clicking cancel or closing the browser)
    and takes away the memory limit,
    as well as the maximum execution time.
*/

function dont_let_it_stop(){shell_exec('php '.__FILE__.' &');}
//this function calls the file itself.

register_shutdown_function('dont_let_it_stop');
//this function will register the function declared above to be used when the script is being terminated

function get_info($f='current')
{
    return str_replace(' kB','',end(explode(':',trim($f(explode(PHP_EOL,file_get_contents('/proc/meminfo')))))))*1024
}
/*
    this function fetches the infos
    'current' fetches the max memory
    'next' fetches the actual used memory
*/

$max=get_info();//maximum memory
$current=get_info('next');//current memory

$imgs=array(imagecreatetruecolor(1e4,1e4));
$color=imagecolorallocatealpha($imgs[$i=0],128,128,128,126);
imagefill($imgs[$i],0,0,$color);
/*
    this creates an array and inserts one image (10000x10000 pixels),
    filling it then with a solid transparent color
*/

$total-=get_info('next');//calculates the space an image takes

while($max-get_info('next')>$total*2)//while the free memory is higher than the memory of 2 images, fill the array
{
    $imgs[$i++]=imagecreatetruecolor(1e4,1e4);
    $color=imagecolorallocatealpha($imgs[$i-1],128,128,128,126);
    imagefill($imgs[$i-1],0,0,$color);
}

//this is just to keep the images in memory, so the script doesn't end
while(1)sleep(60);

This will fill the memory with huge RGBA images (10000x10000 pixels).
The only way to shut this baby down is shutting down the power.
The code is all commented.
Any improvement, doubt, bug or anything, use the comment box below.

Would anybody with access to linux mind testing it? Thanks :)

I have linux, I just am not sure how it will work. I provided the printscreen for the 1st answer, but that is a really old version of puppy linux. Ubuntu is too slow to run php. Maybe I test on my Android later.

it fails the point about not calling another program

It's not calling another program: it's calling the same program that started the file for the same file.

Perl
sub _ {
  my($f,$b);
  $f=\$b;$b=\$f;
}
while(1) { _;}

Uses circular references.  The reference count for the variables will never reach 0, and the references will never be garbage collected.
You might need to be patient, but it is guaranteed to choke your system.  The disk would start spinning faster and fumes might be visible.

Python - 56
class x:
 def __setattr__(self,*args):self.y=0
x().y=0

Creates  a class, defines a method for setting attributes, sets an attribute in it, and creates an initial instance which it then tries to set an attribute of.
A simple recursive function (def f(x):f(x)) seemed a bit unimaginative so I decided never to actually call a function.
Memory management might catch the recursion depth, but it really depends on the implementation.
If this is a fork bomb, please tell me.

This causes no memory exhaustion, just a: RuntimeError: maximum recursion depth exceeded while calling a Python object. Even setting the maximum recursion limit with sys.setrecursionlimit almost no memory is used before it crashes with a segmentation fault.

@Bakuriu Like I said, it really depends on implementation (there are implementations of Python that convert to C(++) and compile, e.g. Shedskin, Nuitka).

Then state for which particular implementation(s) you are writing the code. There is a difference between challenges where only the syntax matter and thus the implementation isn't relevant, and challenges that completely depend on how the language is implemented.

Perl
It's a simple one, but I felt like golfing it.
{$x=[$x];redo}

After two iterations, $x contains a reference to array containing a reference to array containing undef.
Memory usage is linear in time, with small allocations, but it only took several seconds to severely slow my window manager on my Ubuntu Linux system.  Half a minute later the OOM killer took care of it.

Bash
Create an empty file test
Replace /dev/null/ with this text file
$ sudo mv test /dev/null
This works in a similar manner to @Comintern's answer. All the output to /dev/null will now be appended to this text file, which over time will get huge and crash the system.

A huge file would not crash the system. And assuming an average disk size of 500gb it would take a long time for the file to even get near to filling up the disk.

On systems where /dev is a devtmpfs, it may fill up and hinder the system.  I'm guessing that's the intent of this answer.

Bash: 7 chars
This should be the simplest bash solution.  No forks, no cheating.
x=`yes`

You are advised not to run this as root.

Additional note: even if you terminate this with ctrl-c midway, and then unset the variable, the memory remains allocated until the shell is killed.  You can watch the carnage in top.

My own tests with bash 4.2.45(1) show that unset x does free the memory. pdksh also frees the memory, but ksh93 fails to free it, and exit in ksh93 dumps core.

For me (bash 4.3.11(1)), the resident memory display in top for the parent shell climbs steadily until the yes is killed, at which point it just stays there, unset having no effect.  But this is on a large memory system and having a variable that's several gigabytes does not seem to trouble it (until it finally decides to kill the shell).

C
main()
{
    void * buffer;
    while (1)
        buffer = malloc(4096);
}

Well it takes memory page after page and finally there is no memory left.

How universal is a page being 4 KB?

@Peter 4K is often size, but I cannot tell if it is really universal, but page size has no relationships with given question.

@ST3: You should make the memory page dirty. Most modern operating systems use virtual memory and just make a record in the virtual memory table, when you allocate memory. Writing a single byte to the memory page will already force the operating system to map the virtual memory page to physical memory.

See http://codegolf.stackexchange.com/questions/24485/create-a-memory-leak-without-any-fork-bombs/#answer-24492.

C++ 79
void f(char *p,int i){p=new char[i];f(p,++i);}
int main(){char c='a';f(&c,1);}

Non-golfed
void leak(char *p,int i)
{
    p=new char[i];
    leak(p,++i);
}

int main()
{
    char c='a';
    f(&c,1);
}

I fixed my entry to include call from main.

This is a popularity contest. If the program works keep it the main and header. its fine. Also, could you post a non golfed version? Thanks :)

Ruby
a=[];loop{a<<a}

It just endlessly appends (recursive!) self-references to itself.
Found out about this little gem when someone broke my Ruby sandbox with it. :D
Demo of the recursive aspects of it:
[1] pry(main)> a=[]; a<<a; a
=> [[...]]
[2] pry(main)>

perl, 11 chars
I know this isn't code golf, but here's my code-golfy answer, which simply grows the stack indefinitely (you can do that in perl, unlike most C implementations).
sub l{l()}l

Be sure to set ulimit -v before running, it eats a gigabyte per second.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: Георги Кременлиев

sort: votes


text:
Underhanded contest (?): Anti-Virus wars
Prove anti-virus software is paranoid by making a program that simply opens and alphabetically sorts a CSV file, that will get flagged as a virus (or malware/spyware/any threat really) when run.
You will be assessed by the following criteria:

Does the cross-platform anti-virus package ClamAV detect it as a threat?
Your code is not actually a virus (if the code looks fishy it will be deducted points)
Conciseness of code

The specific target for this challenge is the following version of ClamAV with the following virus definitions (current as of the posting of this challenge). Your program must trigger this set of software/definitions to be eligible.
You may wish to use a virtual machine for testing your code.
Latest ClamAV® stable release is: 0.98.1
ClamAV Virus Databases:
main.cvd ver. 55 released on 17 Sep 2013 10:57 :0400 (sig count: 2424225)
daily.cvd ver. 18639 released on 19 Mar 2014 06:45 :0400 (sig count: 839186)
bytecode.cvd ver. 236 released on 05 Feb 2014 12:36 :0500 (sig count: 43)
safebrowsing.cvd ver. 41695 released on 19 Mar 2014 03:00 :0400 (sig count: 1147457)

Try answering a few questions first to gain a few rep, then post your questions as an answer in the sandbox.

Hi Andy! Given the large number of different platforms and AV software out there, it's difficult to use "Does an anti-virus detect it as a threat" as an objective winning criterion. It would help to limit the target to a specific AV package with specific virus definitions. I've edited your post to use a specific free, cross-platform package. However, even with that clarification, it will help to decide clearly on what you want the winning condition for your question to be and tag it accordingly. Generally, popularity contests encourage creativity while code golf encourages conciseness.

"if the code looks fishy it will be deducted points" The whole purpose of this challenge is to write code that looks fishy.

@JonathanVanMatre I think even with this clarification it doesn't make a good popularity contest. The challenge basically says: write some code which sorts csv (whatever that means) and then hide a malware signature inside this code. That is not very specific and interesting in the main task, namely inserting the signature.

@Howard Even so, I am doing my best to practice what I preach.

@JonathanVanMatre It wasn't meant as criticism from my side but merely as a comment. In its current form it is imho no fit for a popularity contest. Currently I don't have an idea how to turn around this challenge and make it suitable. If this question was posted in the sandbox instead maybe someone would have posted an idea how to make it an ok question.

I suggest retagging as code-golf. Shortest code to alphasort a .csv file, trigger ClamAV version , and NOT cause any actual harm wins. This would allow for interesting solutions that mix the signature with the sorting algorithm just so save on bytes.

Tag description on [tag:underhanded] says "...does one thing, but, in reality, does something else" - I don't think this meets the criteria of the tag

@professorfish I feel as though it may be a bit late to change parts of the question, considering it has already been answered

@AndyRama I'm not asking for the question to be changed, I'm just suggesting that the tags be changed

@professorfish I still beleive it meets those criteria. The program looks like a virus but is not one.

I'm closing this question because, by community consensus, underhanded challenges are no longer welcome on the site.

bash (113)
sort -t, "$1"
#PK^C^D^@^@^@^@^@^@^@^@^@^@^@^@^@^@D^@^@^@D^@^@^@^@^@^@^@X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*

The above uses caret notation. Notably, ^@ indicates a null byte.
How it works

sort -t, "$1" sorts the file specified as the first command-line argument ($1), using the comma character as field delimiter (-t,).
# at the beginning of the second line comments it out; it will get ignored by bash.
PK^C^D^@^@^@^@^@^@^@^@^@^@^@^@^@^@D^@^@^@D^@^@^@^@^@^@^@ is the shortest possible ZIP file local file header:

PK^C^D (0x04034B50) is the local file header signature.
^@^@^@^@^@^@^@^@^@^@^@^@^@^@ specifies the ZIP version, a bit flag, the compression method and the compressed file's mtime and checksum. All are set to zero.
The twice occurring D^@^@^@ (0x00000044 or 68) specifies the file's compressed and uncompressed length (68 bytes).
^@^@^@^@ specifies the filename and extra header length. Both are set to zero.

X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H* is the 68 byte long  EICAR test string, which serves as the data associated to the above header.

This takes advantage of the fact that ClamAV will act on all ZIP file local file headers, even if they're encountered outside of actual ZIP files.
Malware scan
VirusTotal gives 15 false positives out of its current 51 scanners. This includes ClamAV.

Nice! If no one one-ups you by Monday night (PST) then you'll be the accepted answer :)

Not a 'false positive'

@JopVernooij: I'd say it is. ClamAV wouldn't act on the EICAR test string if it wasn't because of the ZIP file local file header. However, that header is malformed and there's no end of central directory record, so the data associated to the file header will never get extracted. The fact that I used a test signature instead of actual malicious code doesn't affect the result.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Hidden stereogram message
You must generate an text stereogram according to an input string containing a paragraph of text, an empty line then the hidden message.
The result will be displayed as a pair of paragraphs, one with different spacing causing the effect of it being raised up when viewed stereographically (An explanation can be found here).
Example
Input:
I invented vegetarianism.  It is a diet involving no meat, just vegetables.  It is also common in cows - they are awesome.

vegetarianism. is awesome.

Output:
I      invented    I      invented
 vegetarianism.    vegetarianism.
It   is a  diet    It  is  a  diet
involving    no    involving    no
meat,      just    meat,      just
vegetables.  It    vegetables.  It
is  also common    is  also common
in cows  - they    in cows  - they
are    awesome.    are   awesome.

Bonuses

Add option to choose between parallel and cross-eyed as user input (-20)
Adjustable column width as user input (-50)

This is code golf, so shortest code after bonuses wins.

This is the first time I see a stereogram with text. This is awesome.

They don't work for me :/ (I have eye problems that inhibit stereographic vision)

Holy crap I just saw it... This is impressive!

@Glenn Randers-Pehrson would you mind explaining why you added the [sorting] tag?

It was a mistake.  I thought I was on another question, and cannot find a way to cancel.  If it gets approved then I'll roll it back.

That is trippy. "Vegetarianism is awesome."

It seems like this is really just a text wrapping challenge...

Bash, sed:    228 223 197 (242 - 70) = 172
c=${5:-=};R=$c;L=;for f in r l;do
e="sed -e ";$e"$ d;s/$\|  */ \n/g" $1>m
o=1;for w in `$e"$ p;d" $1`;do
$e"$o,/^$w /s/^$w /$L$w$R /" m>n;o="/$c/"
cp n m;done;tr -d \\n<n|fold -sw${2:-35}|$e"s/$c/ /g">$f
L=$c;R=;done;pr -tmw${3:-80} ${4:-l r}

If the script is in an executable file called "stereo", then type
stereo file.in [column_width [page_width ["r l"]]]

column_width is a number; 25-45 will work, default is 35.
page_width is a number, should be about twice the column_width, default is 80
For cross-eyed viewing, use "r l" as the 4th argument.  Default is "l r" which
sets up for parallel viewing.
EDIT: Rewrote to split the file into one word per line, then reassemble at the end.  Note: reserves the "=" sign for its own use.  Any "=" signs in the input file will become blanks.
EDIT: If your message has "=" signs in it, you can choose another symbol for the script to use, by supplying it as the 5th parameter.
Example
Input: vegetarianism.txt:
I invented vegetarianism.  It is a diet involving no meat, just
vegetables.  It is also common in cows - they are awesome.

vegetarianism. is awesome.

Result
./stereo vegetarianism.txt 32 72 "l r" : | expand
(using the colon for its internal working symbol)
I invented  vegetarianism. It       I invented vegetarianism.  It
 is a diet involving no meat,       is  a diet involving no meat,
just vegetables. It is also         just vegetables. It is also
common in cows - they are           common in cows - they are
 awesome.                           awesome.

./stereo washington.txt 35 75 "l r" |expand
In a little district west of          In a little district west of
 Washington Square the streets        Washington  Square the streets
have run crazy and broken             have run crazy and broken
themselves into small strips          themselves into small strips
called 'places'. These 'places'       called 'places'. These 'places'
make strange angles and curves.       make strange angles and curves.
One Street crosses itself a time      One Street crosses itself a time
or two. An artist once discovered     or two. An artist once discovered
a valuable possibility in this        a valuable possibility in this
street. Suppose a collector with a    street. Suppose a collector with a
bill for  paints, paper and canvas    bill for paints,  paper and canvas
should, in traversing this route,     should, in traversing this route,
suddenly meet  himself coming         suddenly meet himself  coming
back, without a cent having been      back, without a cent having been
paid on account!                      paid on account!

The "|expand" isn't necessary but when shifting the output by 4 places the TABs get handled incorrectly.  It could be put into the script at a cost of 7 bytes.
ImageMagick variation
Replacing the last line with a text-to-image ImageMagick command:
c=${6:-=};R=$c;L=;for f in r l;do
e="sed -e ";$e"$ d;s/$\|  */ \n/g" $1>m
o=1;for w in `$e"$ p;d" $1`;do
$e"$o,/^$w /s/^$w /$L$w$R /" m>n;o="/$c/"
cp n m;done;tr -d \\n<n|fold -sw${2:-35}|$e"s/$c/ /g">$f
L=$c;R=;done;
convert -border 10x30 label:@${4:-l} label:@${5:-r} +append show:

In this one, the "r" and "l" for cross-eyed versus parallel viewing
are separate arguments:
./im_stereo vegetarianism.txt 40 80 l r =

(source: simplesystems.org)
EDIT 3: Added ImageMagick variation.

TeX 212
I am using a typesetting system, not ASCII.  The column width can be changed by changing 90pt in the fourth line, but I don't know if that's enough to qualify for the 50 bytes discount.  The distance between the two copies of the text can be changed by changing the 9pt, also in the fourth line.  The code can probably be made shorter.  One can replace each newline by a single space, but not remove them completely.
\let\e\expandafter\read5to\t\read5to\.\def\a#1
{\def\~##1#1##2\a{\def\t{##1\hbox{\
#1\~{}}##2}\a}\e\~\t\a}\e\a\.{}\shipout\hbox
spread9pt{\hsize90pt\fontdimen3\font\hsize\vbox{\t}\
\let\~\ \def\ {}\vbox{\t}}\end.

After calling tex filename.tex in the terminal, the user is prompted to give the main text, then prompted again for a list of words to shift.  No empty line in between.  The (space-separated) list of words given in the second line should appear exactly as it is in the main text (punctuation is treated just like a letter would be, only spaces delimit words).

I don't have a TeX compiler. Could I see a picture?

I meant adjustable by user input rather than editing the code, otherwise this bonus would apply to almost any code.

Javascript 391 (441 - 50)
(My first code golf)
k=' ';Q='length';A=prompt().split(k);S=prompt().split(k);i=-1;M=25;L=[[]];j=0;R='';while(i++<A[Q]-1){if((j+A[i][Q])<M){if(S.indexOf(A[i])>-1){A[i]=(j?k+k:k)+A[i]}L[L[Q]-1].push(A[i]);j+=A[i][Q]+1}else{j=0;i--;L.push([])}}for(i=0;i<L[Q]-1;P(L[i++].join(C))){C=k;while(L[i].join(C+k)[Q]<M){C+=k}}P(L[i].join(k)+k);function P(a){while(a[Q]<M){a=a.replace(k,k+k)}R+=a;for(c in S){a=a.split(k+k+S[c]).join(k+S[c]+k)}R+=k+k+a+'\n'}console.log(R);

Result
In    a  little  district   In    a  little  district
west    of     Washington   west    of    Washington
Square   the streets have   Square   the streets have
run    crazy  and  broken   run    crazy  and  broken
themselves    into  small   themselves    into  small
strips   called 'places'.   strips   called 'places'.
These     'places'   make   These     'places'   make
strange     angles    and   strange     angles    and
curves.     One    Street   curves.     One    Street
crosses  itself a time or   crosses  itself a time or
two.     An  artist  once   two.     An  artist  once
discovered    a  valuable   discovered    a  valuable
possibility     in   this   possibility     in   this
street.      Suppose    a   street.      Suppose    a
collector   with  a  bill   collector   with  a  bill
for   paints,  paper  and   for  paints ,  paper  and
canvas      should,    in   canvas      should,    in
traversing   this  route,   traversing   this  route,
suddenly   meet   himself   suddenly   meet  himself
coming    back, without a   coming    back, without a
cent  having been paid on   cent  having been paid on
account!                    account!

Long code:
var arr = "In a little district west of Washington Square the streets have run crazy and broken themselves into small strips called 'places'. These 'places' make strange angles and curves. One Street crosses itself a time or two. An artist once discovered a valuable possibility in this street. Suppose a collector with a bill for paints, paper and canvas should, in traversing this route, suddenly meet himself coming back, without a cent having been paid on account!".split(' ');
var secret = "Washington paints himself".split(' ');
var i = -1;
var MAX_WIDTH = 25;
var lines = [[]];
var _l = 0;

var result = '';

while (i++ < arr.length - 1) {
    if ((_l + arr[i].length) < MAX_WIDTH) {
        if (secret.indexOf(arr[i]) > -1) {arr[i] = (_l?'  ':' ') + arr[i]}
        lines[lines.length - 1].push(arr[i]);
        _l += arr[i].length + 1;

    } else {
        _l = 0;
        i--;
        lines.push([]);
    }
}

for (var i = 0; i < lines.length - 1; putText(lines[i++].join(chars))) {
  // Align text
  var chars = ' ';
  while (lines[i].join(chars + ' ').length < MAX_WIDTH) {
    chars += ' ';
  }
}
putText(lines[i].join(' ') + ' ');
function putText(line) {
  while (line.length < MAX_WIDTH) {
    line = line.replace(' ', '  ');
  }
  // Make the illusion
  result += line;
  for (var val in secret) {
    line = line.split('  '+secret[val]).join(' ' + secret[val] + ' ');
  }
  result += ('   ' + line) + '\n';
}
console.log(result);

Nicely done. You can save a bunch (~17) if you add Q='length' and then replace things like A.length with A[Q].

@DocMax thanks, that is a nice trick. I'm new in codegolf, thanks for your suggestion :)

"Washington paints himself"?

Javascript 493 (minimum expectations)
g=" ";l=prompt().split(g);r=l.slice();m=prompt().split(g);f=[];s=f.slice();w=0;n=0;a="";for(i=0;i<l.length;i++){if(l[i]==m[0]){m.shift();l[i]=g+r[i];r[i]+=g;}if(l[i].length+1>w)w=l[i].length+1;}while(l.length){f[f.length]="";s[s.length]="";while(l.length&&f[f.length-1].length+l[0].length<w){f[f.length-1]+=l[0]+g;s[s.length-1]+=r[0]+g;l.shift();r.shift();}f[f.length-1]+=g.repeat(w-f[f.length-1].length);}console.log(f,s);while(f.length){a+=f[0]+s[0]+"\n";f.shift();s.shift();}console.log(a);

This code sets up two arrays of lines (left and right), arranges them in a string and prints to f12 console.
This is just a minimum answer, not intended to win.

418 with JavaScript:
L=b=>b.length;c=console.log;p=prompt;r=(l=p().split(g=" ")).slice(),m=p().split(g),s=(f=[]).slice(),n=w=a="";for(i=0;i<L(l);i++)l[i]==m[0]&&(m.shift(),l[i]=g+r[i],r[i]+=g),L(l[i])+1>w&&(w=L(l[i])+1);for(;L(l);){f[L(f)]="";for(s[L(s)]="";L(l)&&L(f[L(f)-1])+L(l[0])<w;)f[L(f)-1]+=l[0]+g,s[L(s)-1]+=r[0]+g,l.shift(),r.shift();f[L(f)-1]+=g.repeat(w-L(f[L(f)-1]))}for(c(f,s);L(f);)a+=f[0]+s[0]+"\n",f.shift(),s.shift();c(a)

GolfScript 209 (279 -50 -20)
This is my first big GolfScript program.  I wouldn't be surprised if there are optimizations to be had.  Both the bonuses are supported; they are expected to be found after the message inputs, like:
"I invented vegetarianism.  It is a diet involving no meat, just vegetables.  It is also common in cows - they are awesome."

"vegetarianism. is awesome."

16  # column width
0   # view type, 1 for cross eyed (?)

If you've saved that file to input (and downloaded GolfScript) you can invoke the script with:
> cat input | ruby golfscript.rb

Golfed
~{{\}}{{}}if:v;:w;n%~' '%\' '%[.]zip 0:c;{' '*}:s;{[.;]}:r;\{:x;{.c=0=x=}{1c+:c;}until.c<\1c+>[[x' 'v+' 'x v+]]\++}/zip{0:c;[[]]\{.,.c+w<{1c++:c;\)@r+r+}{:c;[r]+}if}/{.{,}%{+}*w\- 1$,1-.{1$1$/@@%@0:g;{3$3$g>+s\++1g+:g;}*\;\;}{[;.2/\2%1$s@@+s@)\;\]{+}*}if}%}%zip{{4s\++}*}%n*puts

Ungolfed
~
#The program:

# Parameters, in reverse natural order

{{\}}{{}}if:v;   # view - truthy for parallel, falsey for cross-eyed
:w;         # col width

n%~         # split input on newlines

' '%\       # split secret message tokens
' '%        # split public message

[.]zip      # left and right

0:c;        # word count

{' '*}:s;   # spaces
{[.;]}:r;   # array of top

# for each secret word
\{

  :x;       # word

  {.c=0=x=}
  {1c+:c;} until
  # next public word is this private word

  # splice edits
  .c< \1c+> [[x' 'v+  ' 'x v+]]\ ++

}/
zip

# layout both messages
{

  0:c;    # char count

  [[]]\   # line accumulator

  # split lines
  {

    .,.c+w<
    # if enough room on line

    #append to current line
    {1c++:c;
    \)@r+r+
    }

    #append as new line
    {:c;
    [r]+
    }if

  }/

  # set lines
  {

    .{,}%{+}* # line chars
    w\-       # space chars
    1$,1-     # gaps between words

    # if multi word
    .{

      1$1$      # duplicate params

      /@@       # chars per space
      %         # extra space gaps

      @         # load line
      0:g;      # current gap

      # join row
      {
        3$3$    # params

        g>+     # extra space
        s       # space chars

        \++     # append

        1g+:g;  # update gap
      }*

      \;\;      # drop params

    }
    # else one word
    {
      [
        ;         # drop gap count
        .         # num spaces needed

        2/\       # spaces per side
        2%        # extra space

        1$s       # left space
        @@+s      # right space

        @)\;\     # word

      ]{+}*     # join

    }if

  }% # end line layout

}% # end message layout

zip

{{4s\++}*}%

n*

puts

JavaScript 391
_='L=b=>b.length;c=console.log;p=prompt;r=(l*=" ")3m*),s=(f=[]3n=w=a52i=0;i<67i++)l/==m@&&(m!,l/=g+r/,r/8g),?>w&&(w=?72;67){9$]52:]56)&&%#)+64)<w;)#8l4+g,:-1]8r@+g,l!,r!;#8g.repeat(w-%#))}2c(f,s7%f7)a8$f4+s4+"\\n",f!,s!;c(a)!.shift()#9-1]$??%L(*=p().split(g/[i]2for(3).slice(),4[0]5="";6%l7);8+=9f[%f):s[%s)?6/)+1@[$0]';for(Y in $='@?:98765432/*%$#!')with(_.split($[Y]))_=join(pop());eval(_)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/