g | x | w | all
Bytes Lang Time Link
020AWK251014T162741Zxrs
004Uiua251011T231514Zphidas
nan251011T074147Zmaledisc
031Rust200813T163343ZTehPers
002Keg200814T083116Zlyxal
015asm2bf200814T082204ZKamila S
002Aceto170529T103413ZL3viatha
014Flurry200813T083326ZEsolangi
005SMBF161201T225606Zmbomb007
002Implicit171125T181437ZMD XF
008Whitespace170529T095557ZEphphath
162VB.NET170406T110242ZDavid
010C170315T212958ZBijan
5804Sinclair ZX80/ZX81 BASIC170405T115951ZShaun Be
055c#170406T063220Zjdt
012OIL170405T120640ZL3viatha
003√ å ı ¥ ® Ï Ø ¿170315T211040Zcaird co
109C#170307T121733ZTheLetha
028C#170215T084320ZMika
002V170215T083313ZDJMcMayh
010BrainFlak170215T073223ZPavel
064Commodore170210T163326ZShaun Be
005sed161201T203138Zzeppelin
018SmileBASIC170206T232038Z12Me21
004Dyalog APL161208T115007ZAdá
018JavaScript161208T095636ZFilip Du
001Labyrinth161202T190259ZStefnotc
104Java161205T133531ZAron_dc
236BotEngine161205T131631ZSuperJed
022F#161205T101909Zpmbanka
014PowerShell161204T063340ZBooga Ro
016Mathematica161204T050951ZEric Tow
008Python161203T213913Zasmeurer
004Perl161203T094844Zprimo
035Ceylon161201T224830ZPaŭlo Eb
nanJAVA161202T031500ZDepresse
nanJava161202T215148Zuser1893
013Python REPL161201T202543ZFlipTack
005Bash + coreutils161201T223638ZDigital
023C linux161201T034304ZDigital
019SAS161202T103126Zuser3490
003Fission161202T143018Zuser4180
013PHP161201T213343ZMonkeyZe
003Microscript II161201T202043ZSuperJed
008TIBASIC161202T105342Zuser5550
003Actually161202T104703Zuser4594
027Kotlin161202T061217ZF. Georg
012tinylisp repl161202T060953ZDLosc
011Haskell using ghc 8.0.1161201T191822Znimi
007dc161202T010909Zfaubi
009WinDbg161201T232313Zmilk
001Funge98 cfunge161201T190541Zuser6213
015C++ using g++ compiler161201T025551ZWheat Wi
005Brainfuck161201T111428Zvsz
007///161201T203207Zsteenber
007TI83 Hex Assembly161201T194742Zhabs
00205AB1E161201T185640ZMagic Oc
003Pushy161201T192047ZFlipTack
011Ruby161201T192037Zdaniero
001><> Fish161201T191504Zredstarc
016Python161201T185312ZFlipTack
019Haskell161201T071839ZAngs
015JavaScript 15 Bytes161201T100301ZLmis
035Python161201T113134ZNoelkd
012Perl161201T030614ZBenGoldb
046Rust161201T091115Zuser6126
101Java161201T081513ZmasterX2
013Racket161201T074307ZWinny
024Haskell161201T065546ZLaikoni
106Java 7161201T053900ZPoke
002BASH161201T042007ZIpor Sir
002Jelly161201T033201ZJonathan
016Python 3161201T034614Zartifici
013Perl 6161201T024643ZBrad Gil

AWK, 20 bytes

END{for(;;)b[++i]++}

Attempt This Online!

This will chew up gigs of ram pretty fast.

Uiua, 4 bytes

⍢1 1

(don't) Try it in the pad!

Repeatedly pushes 1 to the stack. An out of memory error is hard to achieve in Uiua pad due to execution time and array size limits and I didn't want to test it on my computer, but it would (theoretically) work.

Binary encoded lambda calculus: 22 bits

while not realy memory allocation it does need infinite space

0100011010000101101010

More conventional notation: (λx.(x x) λx.((x x) x))

How does that work?

It first beta reduces to (λx.((x x) x) λx.((x x) x))

which then reduces to ((λx.((x x) x) λx.((x x) x)) λx.((x x) x))

then reduces to (((λx.((x x) x) λx.((x x) x)) λx.((x x) x))) λx.((x x) x))

and then to ((((λx.((x x) x) λx.((x x) x)) λx.((x x) x))) λx.((x x) x)) λx.((x x) x))

im sure you see the pattern.

Rust, 35 31 bytes

-4 bytes thanks to madlaina (into_raw -> leak)

||loop{Box::leak(Box::new(0));}

Try it online

Full program, 40 bytes

fn main(){loop{Box::leak(Box::new(0));}}

Try it online

Unlike the other Rust solution, this uses Box::leak to leak the boxed value, turning it into a &'static mut i32.

Keg, 2 bytes

{a

Try it online!

Simply push infinite as

asm2bf - 15 bytes

@l
psh 1
jmp %l

Will push 1 until the interpreter/system runs out of memory.

Aceto, 2 bytes

e>

Pushes e (2.71..) on the stack, and moves the IP back to the first cell.

There are of course many 2-byte solutions in Aceto, (any single character literal (1234567890ePR'), followed by a command that makes the thing infinite (I can think of <>O, but there might be more), but I chose e> because it looks a bit like a heart (<3 sadly doesn't work).

Flurry, 14 bytes

(<>{}{({})}){}

Adapted from this answer. One of the {} terms is replaced with {({})}, a function which pushes its argument to the stack. Thus the infinite loop grows the stack on every iteration.

SMBF, 5 bytes

Although the brainfuck solution also works in SMBF, I decided to create a solution that only works in SMBF.

<[>+]

Since the source is placed on the tape to the left of the pointer, < will move the pointer to point at ], and then we loop, traveling forever on the tape.

Implicit, 2 bytes

(a

Try it online! (Uses up all allowed TIO memory in about 1 second)

(   create jump point
 a  push 97
    implicit infinite loop

Whitespace, 8 bytes


  

 	

Try it online!

Explanation

(s - space, t - tab, n - newline)

nssn ; Declares a label consisting of the empty sequence
nstn ; Call the procedure given by the empty label (declared above)

This is a slight abuse of the rules. The call procedure command jumps to the specified label and marks the current location for a later return. The mechanisms for doing this are implementation dependent but a basic implementation used by many interpreters is to push the current location to a call stack and pop values when a ret command is encountered. This will therefore end up filling up the call stack of the interpreter.


Whitespace, 12 bytes - Fills the stack


  
   

 


Try it online!

Explanation

nssn ; Declare label ''
sssn ; Push 0
nsnn ; Jump to label ''

Continuously pushes the value 0 to the stack, causing the stack to grow until the interpreter crashes.


Whitespace, 29 bytes - Fills the heap

   	

  
 
 	    
  
 		 
 


Try it online!

Explanation

ssstn ; push 1
nssn  ; label ''
sns   ; duplicate n
tsss  ; add (effectively multiplies by 2)
sns   ; duplicate n (to use as a heap address)
sns   ; duplicate n (to use as a value)
tts   ; store n at the address n
nsnn  ; jump ''

Fills heap addresses given by 2^n with the value of 2^n, starting at n=1. Consumes memory faster on interpreters that implement the heap as an array but will also work for interpreters that use a non-contiguous data structure backing the heap (such as a dictionary/map).

VB.NET, 162 bytes

Module m
    Sub Main()
        Dim s = ""
        While (1)
            s = s + "1" : Threading.Thread.Sleep(2147483647)
        End While
    End Sub
End Module

It won't really run forever but close enough. It should take about 584942417 years to allocate 8gb.

C, 10 bytes

f(x){f();}

The x is needed for memory to be used in addition to stack space. This will endlessly make calls to itself each time taking ~32bits to store x.

Sinclair ZX80/ZX81 BASIC, ~14 bytes ~7 bytes (ZX81/ZX80 8K ROM), ~10 bytes ~5 bytes (ZX80 4K ROM)

 1 GOSUB 1

As there is never a return from the GOSUB (presented as GO SUB on the ZX80 with 4K ROM), the stack is filled which will eventually cause the interpreter to error. To clear the stack, simply enter NEW which should initiate a soft reset.

c#, 55 bytes

class c{static void Main(){string c="";for(;;)c+='c';}}

Alternative 54 bytes

class c{static void Main(){string c="c";for(;;)c+=c;}}

OIL, 12 bytes

Here in annotated form (remove anything but numbers to run):

1 # copy
-1 # from line -1 (containing, by default, a 0)
6 # to line 6 (the first line after the last line) %
8 # increment
2 # line 2 (marked with %)
6 # goto (since the next line will now be 0, go to line 0)

Even though seemingly nothing changes (lines are 0 by default and are being set to 0), internally, there's a difference between an unallocated line and a line with an explicit 0 in it.

√ å ı ¥ ® Ï Ø ¿ , 3 bytes

(1)

Explanation

(   › Start an infinite loop
 1  › Push 1 to the stack
  ) › End an infinite loop

C#, 109 bytes

public class P{static void Main({for(;;)System.Xml.Serialization.XmlSerializer.FromTypes(new[]{typeof(P)});}}

Cross posted from here because it answers this question nicely as well.

We found the idea behind this leak in production code and researching it leads to this article. The main problem is in this long quote from the article (read it for more info):

Searching my code for PurchaseOrder, I find this line of code in page_load of one of my pages XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder), new XmlRootAttribute(“”));

This would seem like a pretty innocent piece of code. We create an XMLSerializer for PurchaseOrder. But what happens under the covers?

If we take a look at the XmlSerializer constructor with Reflector we find that it calls this.tempAssembly = XmlSerializer.GenerateTempAssembly(this.mapping, type, defaultNamespace, location, evidence); which generates a temp (dynamic) assembly. So every time this code runs (i.e. every time the page is hit) it will generate a new assembly.

The reason it generates an assembly is that it needs to generate functions for serializing and deserializing and these need to reside somewhere.

Ok, fine… it creates an assembly, so what? When we’re done with it, it should just disappear right?

Well… an assembly is not an object on the GC Heap, the GC is really unaware of assemblies, so it won’t get garbage collected. The only way to get rid of assemblies in 1.0 and 1.1 is to unload the app domain in which it resides.

And therein lies the problem Dr Watson.

Running from the compiler in Visual Studio 2015 and using the Diagnostic Tools Window shows the following results after about 38 seconds. Note the Process memory is steadily climbing and the Garbage Collector (GC) keeps running but can't collect anything.

Diagnostic Tools Window

C#, 28 bytes

()=>{var _="a";for(;;)_+=_;}

What is there to say? It adds the contents of _ to _ forever. Throws OutOfMemoryException almost instantly.

V, 2 bytes

òé

You can try it online, even though it won't output anything.

This simply fills up the interal "buffer" with the ÿ character (0xFF) until the end of time.

Brain-Flak, 10 bytes

(()){(())}

Try it online!

Commodore 64

If ?STRING TOO LONG ERROR counts, then this will work on the Commodore 64 and VIC-20:

0 a$=a$+" ":goto

or if you need ?OUT OF MEMORY ERROR then:

0 dim a(255,255)

However, the last solution does not use a loop as the error is reported as soon as run is entered.

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

Try It Online !

SmileBASIC, 18 bytes

@L
A$=A$+@A
GOTO@L

Keeps creating strings consisting of @A@A@A.... It would be much faster to use PUSH to modify the original string, but that would use more characters.

Dyalog APL, 4 bytes

⊂⍣≡⍬

enclose

until

identical to the previous iteration (i.e. never, as each iteration has one more level of enclosure)

empty (numeric) list

The program starts as follows:

[], enclose that, yielding

[[]]. Is that identical to []? No, so we enclose that, yielding

[[[]]]. Is that identical to [[]]? No, so we enclose that...

Since each enclosure needs a new pointer, memory usage will slowly increase until WORKSPACE FULL.

JavaScript - 14 18 bytes

while(x=[self.x]);

Based on the activity on @Lmis' answer, some fun with evaluating expressions in intermediate scopes. Didn't manage to avoid reference errors :'(!

Labyrinth, 1 byte

_

This keeps pushing a 0 to the stack.

Java 104 bytes

import java.util.*;class A{public static void main(String[]a){List b=new ArrayList();for(;;)b.add(1);}}

This will allocate a List and let it grow constantly until it runs out of space.

BotEngine, 2x3=6

ve<
>e^

Rough translation:

forever:
  enqueue 'e'
  enqueue 'e'

F#, 22 bytes

let rec f x=f(1::x);()

Call it in F# interactive passing an empty list: f []

The function recursively calls itself, adding elements to the list. The tuple at the end is there so that the type inference can determine that the function return type is unit.

PowerShell, 14 bytes

for(){$i+="z"}

Infinite loop creates a variable(string) and appends new characters to the end. Unbearably slow, took over an hour to consume two megabytes. Verified it would consume all the RAM available using something a bit faster: for(){$i+=("z"*9MB)}

Mathematica, 16 bytes

For[i=0,0<1,i++]

Endlessly adds 1 to an arbitrary precision integer, causing its representation in memory to slowly grow.

Might also be the slowest submission since memory allocated only grows logarithmically with time. In fact, I've only let it run to several hundred billion, which barely alters allocated memory. So how do I know it grows without bound? Try the variant

For[i = 1, 0 < 1, i += i]

so that the memory usage is now linear in time... (If you want to watch i,

Monitor[For[i = 1, 0 < 1, i += i], i]

and notice, for instance, that the front end is allocating memory to hold the displayed values faster than the kernel is, because the binary representation is much less fluffy that the decimal representation and resulting graphical object. I suppose one could stress test one's 2D video acceleration by switching to the console interface and running the Monitor[] there... Heh.)

Python, 8 bytes

2**9**99

The OP 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 puts that as 10^76 larger than the deep web (keep in mind that there are about 10^80 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).

Perl, 4 bytes

do$0

Executes itself, in the current interpreter. When finished, execution returns to the calling script, which requires a call stack.

Ceylon, 55 54 35 bytes

shared void r(){variable Object x=0;while(0<1){x=[x];}}

This is a simple while loop, which creates a one-element tuple containing the previous value, i.e. an ever-growing linked list.

I get an OutOfMemoryError (with the default JVM settings on my computer) after:

real    5m42.727s
user    21m31.200s
sys     0m3.472s

5m42s (using 21 minutes of processor time, says time).

Even shorter is the "functional" approach (which in effect does exactly the same):

shared void r(){loop<Object>(0)((x)=>[x]).each(noop);}

Unfortunately I need the type parameter here, otherwise Ceylon assumes Integer (which is the type of 0) and complains that [0] is not an Integer.

The second version is much slower (I've let it run overnight):

real    197m26.677s
user    770m9.300s
sys     1m23.744s

A different approach is just filling a really big sequence of integers:

shared void r(){max((1:9^9)*.not);}

1:9^9 is a Measure<Integer> (an Iterable containing 9^9 elements, starting with 1), by itself not having lots of memory (just the two numbers). But the *.not attribute spread creates a big ArraySequence with the value of i.not for each element of the Iterable. We need to do something with the result (otherwise the compiler complains that this is not a statement), therefore the max(...). The max function is never called here, because this gives an OutOfMemoryError (with "GC overhead limit exceeded") after 6 minutes while trying to build and fill the array:

real    6m23.948s
user    23m46.956s
sys     0m5.200s

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.

Java, 127+19=146

Golfed:

import java.util.*;class A{public static void main(String[]q){List l=new LinkedList();for(;;){String s="";for(int i=0;i>-1;++i)s+=' ';l.add(s);}}}

Ungolfed:

import java.util.*;

public class A {
  public static void main(String[] args) {
    List<String> l = new LinkedList<>();
    for (;;) {
      String s = new String();
      for (int i = 0; i > -1; ++i) {
        s += ' ';
      }
      l.add(s);
    }
  }
}

This program does not rely on the garbage collector or finalize() method like the other Java answers do. Java only interns and merges strings that are constructed from literals, unless specifically interned. That means this program will end up creating strings of size 231 essentially forever, assuming LinkedList works as expected.

Python REPL, 13 bytes

9
while 1:_*9

The first line, 9, sets the built-in _ (last-integer) variable to 9. The infinite loop then keeps setting this to itself multiplied by 9.

Python integers have no upper limit, so this will keep growing until MemoryError.

This only works in the shell, where the _ variable is available. This is allowed by meta.

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.

C (linux), 23 bytes

main(){while(sbrk(9));}

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.

SAS, 75 19

SAS doesn't really lend itself to golfing but I thought I'd have a go, and at least it beats Java some of the Java answers quite a lot of stuff, actually.

Original submission:

data;dcl hash h();h.definekey('i');h.definedone();a:i+1;h.add();goto a;run;

This creates a hash object and keeps adding new values to it until SAS runs out of memory. None of the hash operations fail prior to that point, so no need to capture any pesky return codes for them. SAS does have do loops, but goto saves a few characters.

New submission:

%macro a;%a%mend;%a

Much simpler - a trivial recursive macro. If left running for long enough, it eventually fails with an out of memory error. Both submissions assume that SAS was invoked with option memsize = 0, otherwise it will instead fail when it hits that limit if it is lower than the available system memory.

Fission, 3 bytes

RX+

Continuously creates atoms and increments its mass.

Try it online!

R                 creates an atom moving right
 X                clones atom, one keeps moving to the right, the other gets reflected left
  +               increment the atom's mass

Because of wrapping, this program will continuously create atoms with non-negative mass

Another alternative:

RX'

R and X works like you expect it to, and ' sets the atom's mass to the ASCII value of the next character it hits, ie 'R' (because of wrapping). Thus, this continuously creates atoms with the ASCII value of 'R'.

PHP, 14 13 bytes

Saved a byte thanks to Alex Howansky

while($a.=1);

Indefinitely builds a string of 111111111111...

Microscript II, 3 bytes

1[s

Rough translation:

x=1
while x
  push x

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

Actually, 3 bytes

1W1

Try it online!

This is an infinite loop that pushes a 1 to the stack each time it runs. Actually is implemented in Python, and its stack is a deque, so, despite the name, all memory is dynamically allocated on the heap.

Kotlin, 27 bytes

var o=Any()
while(1>0)o={o}

Stacking functions returning functions.

54 bytes if no .kts: fun main(a:Array<String>){var o=Any();while(1>0)o={o}}

tinylisp repl, 12 bytes

(d f(q(L(f L

Defines a function f that will keep allocating memory when called. If submissions must be full programs, here's a 15-byte solution:

((v(d f(q(L(f L

Explanation

The repl supplies missing parens at the end of the line, so the code is really (d f(q(L(f L)))).

(d f(q(...))) defines f to be the unevaluated list (...). In tinylisp, functions are simply two-element lists. The first element is the parameter list and the second is the function body. Here, the first element is L, which (because it's not wrapped in parentheses) makes this a variadic function in which the entire argument list is assigned to L. The function body (f L) simply calls f again with L as its argument.

This is tail recursion, so the call stack doesn't come into play. But notice what happens to L on successive calls:

(f)        Called with no arguments; L gets empty list ()
(f ())     Called with one argument, empty list; L gets (())
(f (()))   Called with one argument, (()); L gets ((()))

And so on, wrapping the argument in another layer of list each time.

Haskell (using ghc 8.0.1), 11 bytes

m@main=m>>m

Non-tail recursion. main calls itself and then itself again.

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.

WinDbg, 9 bytes

as/c a z1

This works by creating a string of infinite length. as /c Sets an alias (here called a) to the result of the following command(s): z 1 is an infinite do while loop that also prints a line when the while condition is true: redo [###] {redone_code}. So a will be set to a string like:

redo [1] z1
redo [2] z1
redo [3] z1
.
.
.
redo [23489723984] z1
.
.
.

Funge-98 (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).

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

Brainfuck, 5 bytes

+[>+]

This requires an interpreter that has no limit on the length of the tape.

///, 7 bytes

/a/aa/a

Constantly replace a with aa, ad nauseum.

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.

05AB1E, 2 bytes

[A

Try it online! 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.

Pushy, 3 bytes

1$a

Just keeps pushing to the stack...

1     % Push 1
$     % While last item != 0 (forever):
a     %   Push char-codes of the lowercase alphabet

This is just one example: several 3 byte solutions exist, such as 1$1, 1$&, 9$9, etc - anything that will "infinitely" push to the stack.

Ruby, 11 bytes

loop{$*<<9}

Keeps pushing 9 onto $*, which is an array initially holding the command line arguments to the Ruby process.

><> (Fish), 1 byte

0

Try it here!

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.

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.

Haskell, 23 19 bytes

main=print$sum[0..]

Print the sum of an infinite list

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

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.

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

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.

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

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.

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.

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.

BASH, 2 bytes

$0

Parameter $0 is the filename of the script, so it will call itself forever.

Jelly, 3 2 bytes

-1 byte thanks to Dennis (W wraps)

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

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

Perl 6, 13 bytes

@= eager 0..*

Explanation:

@ = store the result into an unnamed array

eager make the following list eager

0 .. * infinite range starting at zero