[Question]
  [
Write a program which runs forever and allocates more and more memory on the heap the longer it runs, at least until you reach the limit of the operating system on the amount of memory that can be allocated.
Many kernels won't actually reserve memory you allocate until you use it for something, so if your program is in C or some other low level language you'll have to make sure you write something to each page. If you're using an interpreted language, you're probably not going to have to worry about this.
Shortest code wins.
  
[Answer]
# Funge-98 ([`cfunge`](https://launchpad.net/cfunge)), 1 byte
```
9
```
I would have posted this earlier, but decided to test it, and it took a while to get my computer back to a usable state. `cfunge` stores the Funge stack on the operating system's heap (which is easily verifiable by running the program with a small memory limit, something that I should have done earlier!), so an infinitely growing stack (as with this program, which just pushes `9` repeatedly; Funge programs wrap from the end of a line back to the start by default) will allocate memory forever. This program likely also works in some Befunge-93 implementations.
More interesting:
```
"NULL #(4
```
This was my first idea, and is an infinite allocation that doesn't rely on the Funge stack (although it blows up the Funge stack too). To start with, the `"` command pushes a copy of the rest of the program to the stack (it's a string, and the program wraps round, so the close quote also serves as the open quote). Then the `N` reflects (it has no meaning by default), causing the program to run backwards. The `"` runs again, and pushes the program to the stack – the other way round this time, with the `N` at the top of the stack – then the program wraps around, loading a library with a 4-letter name (`4(`; the `NULL` library is part of `cfunge`'s standard library). `NULL` defines all uppercase letters to do reflect, so the `L` reflects, the `#` skips the library load on the way back, the `4` pushes junk we don't care about to the stack and the whole program repeats from the start. Given that loading a library multiple times has an effect, and requires the library's command list to be stored once for each copy of the library (this is implied by Funge-98's semantics), it leaks memory via non-stack storage (which is an alternative method of defining "heap", relative to the language rather than the OS).
[Answer]
## Brainfuck, 5 bytes
```
+[>+]
```
This requires an interpreter that has no limit on the length of the tape.
[Answer]
# Bash + coreutils, 5
or
# Ruby, 5
```
`yes`
```
`yes` produces endless output. Putting `yes` in backticks tells the shell to capture all output and then execute that output as a command. Bash will continue allocating memory for this unending string until the heap runs out. Of course the resulting output would end up being an invalid command, but we should run out of memory before that happens.
Thanks to @GB for pointing out this is a polyglot in ruby too.
[Answer]
# Python, 16 bytes
Keeps nesting `a` until an error is reached:
```
a=0
while 1:a=a,
```
The first few iterations (as tuples) look like this:
```
0
(0,)
((0,),)
(((0,),),)
```
and so on and so forth.
[Answer]
## ><> (Fish), 1 byte
```
0
```
[Try it here!](https://fishlanguage.com/playground/oQ5qkLuN8MgLfR5L5)
`0` can actually be substituted for any hexadecimal number 1-f.
**Explanation**
`0` in ><> simply makes a 1x1 codebox for the fish to swim in. It constantly adds a `0` onto the stack, swims right, which loops backaround to `0`, adding it to the stack again. This will go on forever.
[Answer]
## Perl, 12 bytes
```
{$"x=9;redo}
```
In perl, the `x` operator, with a string on the left and a number on the right, produces a repeated string. So `"abc" x 3` evaluates to `"abcabcabc"`.
The `x=` operator mutates the left argument, replacing contents of the variable on its left with the result of repeating it's contents as many times as its right hand side indicates.
Perl has a number of a number of strangely named built in variables, one of which is `$"`, whose *initial* value is a single space.
The `redo` operator jumps to the beginning of the enclosing `{}`.
The first time the `x=` operator is done, it changes the value of `$"` from `" "`" to `" "`, which is 9 spaces.
The second time the `x=` operator is done, it changes the value of `$"` to `" "`, which is 81 spaces.
The third time, `$"` becomes a 729 byte long string of spaces.
I think you can see where this is going :).
[Answer]
## Java 101 bytes
```
class A{public void finalize(){new A();new A();}public static void main(String[]a){for(new A();;);}}
```
Catching main Program in a endless Loop after creating and throwing away a object. Garbage collection does the job of leaking by creating 2 objects for each deleted ones
[Answer]
# sed, 5 bytes
**Golfed**
```
H;G;D
```
**Usage (any input will do)**
```
sed 'H;G;D' <<<""
```
**Explained**
```
#Append a newline to the contents of the hold space, 
#and then append the contents of the pattern space to that of the hold space.
H
#Append a newline to the contents of the pattern space, 
#and then append the contents of the hold space to that of the pattern space. 
G
#Delete text in the pattern space up to the first newline, 
#and restart cycle with the resultant pattern space.
D
```
**Screenshot**
[![enter image description here](https://i.stack.imgur.com/hRBzu.gif)](https://i.stack.imgur.com/hRBzu.gif)
[Try It Online !](https://tio.run/nexus/bash#@1@cmqKg7mHtbu2irmBjY6Ok9P8/AA)
[Answer]
# Haskell, ~~23~~ 19 bytes
```
main=print$sum[0..]
```
Print the sum of an infinite list
[Answer]
## ///, 7 bytes
```
/a/aa/a
```
Constantly replace `a` with `aa`, ad nauseum.
[Answer]
# C++ (using g++ compiler), ~~27~~ ~~23~~ 15 bytes
*Thanks to Neop for helping me to remove 4 bytes*
This solution does not really leak any memory because it allocates everything on the stack and thus causes a stack overflow. It is simply infinitely recursive. Each recursion causes some memory to be allocated until the stack overflows.
```
main(){main();}
```
## Alternative solution
This solution actually leaks memory.
```
main(){for(;;new int);}
```
## Valgrind output
This is the Valgrind output after terminating the program several seconds into the run time. You can see that it is certainly leaking memory.
```
==2582== LEAK SUMMARY:
==2582==    definitely lost: 15,104,008 bytes in 3,776,002 blocks
==2582==    indirectly lost: 0 bytes in 0 blocks
==2582==      possibly lost: 16 bytes in 4 blocks
==2582==    still reachable: 4 bytes in 1 blocks
==2582==         suppressed: 0 bytes in 0 blocks
```
[Answer]
# JAVA, ~~81~~ ~~79~~ 78 bytes
# JAVA (HotSpot) ~~71~~ 70 bytes
Shorter than other Java answers at the time I posted (81, later 79 bytes):
```
class A{public static void main(String[]a){String x="1";for(;;)x+=x.intern();}}
```
As suggested by @Olivier Grégoire, a further byte can be saved:
```
class A{public static void main(String[]a){for(String x="1";;)x+=x.intern();}}
```
Placing `x+=x.intern()` as the for loop increment would not help anything, because a semicolon is still required to end the for statement.
As suggested by @ETHproductions, just using `x+=x` works too:
```
class A{public static void main(String[]a){String x="1";for(;;)x+=x;}}
```
Which can also benefit from @Olivier Grégoire's tip:
```
class A{public static void main(String[]a){for(String x="1";;)x+=x;}}
```
My only misgivings about that is that it is not guaranteed to allocate data *on the heap*, as an efficient JVM can easily realize that `x` never escapes the local function. Using `intern()` avoids this concern because interned strings ultimately end up stored in a static field. However, HotSpot does generate an `OutOfMemoryError` for that code, so I guess it's alright.
Update: @Olivier Gregoire also pointed out that the `x+=x` code can run into `StringIndexOutOfBoundsException` rather than `OOM` when a lot of memory is available. This is because Java uses the 32-bit `int` type to index arrays (and Strings are just arrays of `char`). This doesn't affect the `x+=x.intern()` solution as the memory required for the latter is quadratic in the length of the string, and should thus scale up to on the order of 2^62 allocated bytes.
[Answer]
# [Perl 6](https://perl6.org), 13 bytes
```
@= eager 0..*
```
## Explanation:
`@ =` store the result into an unnamed array
`eager` make the following list eager
`0 .. *` infinite range starting at zero
[Answer]
# Python 3, 16 bytes
```
i=9
while 1:i*=i
```
This comes from the fact that there is no limit to integer size in Python 3; instead, integers can take up as much memory as the system can handle (if something about my understanding of this is wrong, do correct me).
[Answer]
## Rust, 46 bytes
```
fn main(){loop{std::mem::forget(Box::new(1))}}
```
Notice something interesting about this Rust program, leaking heap allocations until out of memory?
That's right, no unsafe block. Rust guarantees memory safety in safe code (no reading of uninitialized data, read after free, double free etc.), but memory leaks are considered perfectly safe. There's even an explicit function to make the compiler forget about RAII cleanup of out of scope variables, which I use here.
[Answer]
# TI-83 Hex Assembly, 7 bytes
```
PROGRAM:M
:AsmPrgm
:EF6A4E
:C3959D
:C9
```
Creates appvars indefinitely until an `ERR:MEMORY` is thrown by the OS. Run with `Asm(prgmM)`. I count each pair of hex digits as one byte.
[Answer]
# Python, 8 bytes
```
2**9**99
```
The [OP](https://codegolf.stackexchange.com/questions/101709/shortest-program-that-continuously-allocates-memory?noredirect=1#comment247805_101709) has allowed the technicality of a program that doesn't technically run "forever", but allocates more memory than any computer could possibly handle. This isn't quite a googolplex (that would be `10**10**100`, 11 bytes), but naively, log base 2 of the number is
```
>>> 9**99.
2.9512665430652752e+94
```
i.e., 10^94 bits to represent it. [WolframAlpha](http://www.wolframalpha.com/input/?dataset=&i=2.9512665430652752e%2B94+bits) puts that as 10^76 larger than the deep web (keep in mind that there are about 10^80 [atoms in the universe](http://www.wolframalpha.com/input/?dataset=&i=atoms+in+the+universe)).
Why 2 instead of 9 you ask? It doesn't make much of a difference (using 9 would only increase the number of bits by a factor of `log2(9) = 3.2`, which doesn't even change the exponent). But on the other hand, the program runs much faster with 2, since the calculation is simpler. This means it fills up memory immediately, as opposed to the 9 version, which takes a little longer due to the calculations required. Not necessary, but nice if you want to "test" this (which I did do).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to Dennis (`W` wraps)
```
Wß
```
A link (i.e. function or method), which also works as a full program, that recursively wraps its input into a list.
The input starts as zero so the first pass creates the list `[0]`  
The second pass then makes this `[[0]]`  
The third pass then makes this `[[[0]]]`  
and so on...
---
Previous 3 byter, which leaks much faster:
```
;Ẇß
```
recursively concatenates all non-empty contiguous sublists of its input to its input.  
`[0]` -> `[0,[0]]` -> `[0,[0],[0],[[0]],[0,[0]]]` and so on...
[Answer]
# Java 7, 106 bytes
```
class A{public void finalize(){for(;;)Thread.yield();}public static void main(String[]a){for(;;)new A();}}
```
### Less Golfed
```
class A{
    @Override
    public void finalize(){
        for(;;) {
            Thread.yield();
        }
    }
    public static void main(String[]a){
        for(;;){
            new A();
        }
    }
}
```
The `finalize` method is called on an object by the garbage collector when garbage collection determines that there are no more references to the object. I have simply redefined this method to loop forever so the garbage collector never actually frees the memory. In the `main` loop I create new objects which will never be cleaned up so eventually this will use up all the available memory.
# Java 7 (fun alternative), 216 bytes
```
import sun.misc.*;class A{public static void main(String[]a)throws Exception{java.lang.reflect.Field f=Unsafe.class.getDeclaredField("theUnsafe");f.setAccessible(1>0);for(;;)((Unsafe)f.get(null)).allocateMemory(9);}}
```
### Less Golfed
```
import sun.misc.*;
class A{
    public static void main(String[]a)throws Exception{
        java.lang.reflect.Field f=Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe u = (Unsafe)f.get(null);
        for(;;) {
            u.allocateMemory(9);
        }
    }
}
```
This is a fun one more than anything else. This answer makes use of the `Unsafe` Sun library which is an undocumented internal API. You may need to change your compiler settings to allow restricted APIs. `Unsafe.allocateMemory` allocates a specified amount of bytes (without any boundary checking) which is not on the heap and **not** under java's garbage collector management so this memory will stick around until you call `Unsafe.freeMemory` or until the jvm runs out of memory.
[Answer]
# Haskell, 24 bytes
```
f x=f$x*x
main=pure$!f 9
```
The main problem in Haskell is to beat the laziness. `main` needs to have some `IO` type, so simply calling `main=f 9` would not work. Using `main=pure(f 9)` lifts the type of `f 9` to an `IO` type. However using constructs like `main=pure 9` does not do anything, the `9` is returned or displayed nowhere but simply discarded, so there is no need to evaluate the argument of `pure`, hence `main=pure(f 9)` does not cause any memory to be allocated as `f` is not called.
To enforce evaluation, the `$!` operator exists. It simply applies a function to an argument but evaluates the argument first. So using `main=pure$!f 9` evaluates `f` and hence continuously allocates more memory.
[Answer]
## dc, 7 bytes
```
[ddx]dx
```
`[ddx]` pushes a string containing "ddx" to the stack. `dx` duplicates it then executes it as code (leaving one copy on the stack). When executed, it makes two duplicates then executes one, leaving one more copy on the stack each time.
[Answer]
## Haskell (using ghc 8.0.1), 11 bytes
```
m@main=m>>m
```
Non-tail recursion. `main` calls itself and then itself again.
[Answer]
# C (linux), 23 bytes
```
main(){while(sbrk(9));}
```
[`sbrk()`](https://en.wikipedia.org/wiki/Sbrk) increments the top of the data segment by the given number of bytes, thus effectively increasing the amount of memory allocated to the program - at least as reported in the `VIRT` field of `top` output. This only works on Linux - the macOS implementation is apparently an emulation that only allows allocation of up to 4MB.
---
So a slightly more general answer:
# C, 25 bytes
```
main(){while(malloc(9));}
```
I watched it on the macOS Activity Monitor. It went all the way up to about 48GB, then eventually the process received a SIGKILL signal. FWIW my macbook pro has 16GB. Most of the memory used was reported as compressed.
Note that the question effectively requires each allocation to be written to, which doesn't happen explicitly here. However it is important to note that for every `malloc(9)` call, it is not just the 9 user requested bytes that are allocated. For each block allocated there will be a malloc header that is also allocated from somewhere on the heap, which is necessarily written to by the `malloc()` internals.
[Answer]
# Perl, 4 bytes
```
do$0
```
Executes itself, in the current interpreter. When finished, execution returns to the calling script, which requires a call stack.
[Answer]
# Racket, 13 bytes
```
(let l()(l)1)
```
I'm not entirely certain if my answer falls under this question. Please let me know if I should remove this answer.
[Answer]
# JavaScript ~~22~~ ~~21~~ ~~17~~ ~~16~~ 15 Bytes
```
for(a=0;;)a=[a]
```
Saved 4 bytes by wrapping the list in another list as in @Jonathan Allan's Jelly answer.
Saved 1 byte thanks to @ETHProductions
### Alternative solution 15 Bytes (only works with proper tail calls)
```
f=a=>f([a]);f()
```
[Answer]
# Ruby, 11 bytes
```
loop{$*<<9}
```
Keeps pushing `9` onto `$*`, which is an array initially holding the command line arguments to the Ruby process.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 2 bytes
```
[A
```
[Try it online!](http://05ab1e.tryitonline.net/#code=W0E&input=)
Will just keep pushing `abcdefghijklmnopqrstuvwyxz` onto the stack for eternity.
**All possible 2-byte solutions:**
```
[  # Infinite loop.
 A # Push alphabet.
 0 # Push 0.
 1 # Push 1.
 2 # Push 2.
 3 # Push 3.
 4 # Push 4.
 5 # Push 5.
 6 # Push 6.
 7 # Push 7.
 8 # Push 8.
 9 # Push 9.
 T # Push 10.
 X # Push 1.
 Y # Push 2.
 ® # Push -1.
 ¶ # Push \n.
 º # Push len(stack) > 0, so 0 once then 1 for eternity.
 ð # Push a space.
 õ # Push an empty string.
 ¾ # Push 0.
 ¯ # Push [].
 M # Push -inf.
 ) # Wrap current stack in an array.
```
[Answer]
## Python, 35 bytes
```
def f(a=[]):a.append(a)
while 1:f()
```
`a` is never released and just gets bigger until you hit a `MemoryError`
You can view the execution on [Python Tutor](http://pythontutor.com/visualize.html#code=def%20f(a%3D%5B%5D%29%3Aa.append(a%29%0Awhile%201%3Af(%29%0A&cumulative=false&curInstr=17&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=2&rawInputLstJSON=%5B%5D&textReferences=false).
[Answer]
## TI-BASIC, 8
```
:Lbl A
:While 1
:Goto A
```
(all 1-byte tokens, and two newlines)
This continuously leaks memory because structured control flow such as `While` anticipated being closed by an `End` and pushes something on the stack (not the OS stack, a separate stack in heap memory) to keep track of that. But here we're using `Goto` to leave the loop (so no `End` is executed to remove the thing from the stack), the `While` is seen again, the thing gets pushed again, etc. So it just keeps pushing them until you get `ERR:MEMORY`
]