Shortest program that continuously allocates memory

49

8

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.

tbodt

Posted 2016-12-01T02:26:28.570

Reputation: 2 176

13Is a stack overflow a valid solution? Does the memory have to be leaked or just allocated? – Post Rock Garf Hunter – 2016-12-01T03:02:39.910

1@WheatWizard The memory does not have to be leaked, but it has to be allocated faster than it is deallocated. – tbodt – 2016-12-01T17:16:53.130

2The one time I want my program to consume infinite memory, I can't get it to. (reduce conj [] (range)) (Clojure) gets up to 737mb, then just stops growing. Idk how it's not continually going up. It "thinks" I want to print the entire list at the end, so it shouldn't be throwing anything away. Very frustrating. – Carcigenicate – 2016-12-02T01:05:39.410

14Note to self: Save code before testing. Introducing mem-leaks might crash IDE... – steenbergh – 2016-12-02T09:03:00.553

@steenbergh Ya, happened to me too. At least a 10 bytes solution is easy to rewrite :D – Carcigenicate – 2016-12-02T15:02:54.430

Would a program that computes a googolplex count? It wouldn't run "forever" in the technical sense, but it would use up all the resources of any computer. – asmeurer – 2016-12-03T18:09:27.590

@asmeurer I guess so... – tbodt – 2016-12-03T18:13:26.090

1I think you should add another golf challenge, similar but separate to this, requiring the program consume memory faster than a linear function of time. For the current challenge, looping forever and allocating a single byte should be fine. For your new challenge, that would be insufficient, but looping forever and doubling the amount of memory used each time would be ok. – BenGoldberg – 2016-12-17T18:30:47.523

Answers

46

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

user62131

Posted 2016-12-01T02:26:28.570

Reputation:

2I'm just going to accept this... – tbodt – 2016-12-01T19:08:16.297

Is it necessary for the number to be 9? Would it also work if it was 5? – tbodt – 2016-12-01T19:09:00.590

Anything that pushes to the stack works (except possibly 0; it's possible that the Funge implementation or the OS could find a way to optimize that out, given that the memory in question is full of zeroes already). I just picked 9 arbitrarily. – None – 2016-12-01T19:10:08.187

22Unaccepting because I want my reputation to still be 666. – tbodt – 2016-12-01T19:18:02.343

7@tbodt Not a real reason to not accept. If you'd like, I'll -1 your question. Then when you accept, you'll have 703 still (note you have 703 now, not 666). – NoOneIsHere – 2016-12-01T23:20:27.857

Wouldn't "LLUN"4( also have the same intended effect as the second program, for one less character and a lot less complexity? – user253751 – 2016-12-02T00:08:48.473

@immibis: Yes. The original was "NULL(4, but it didn't work because I forgot what NULL did. (Perhaps some other library would work; it'd need to define fairly benign commands corresponding to the letters of its name. I might look into that when I'm less tired.) I edited it into a working version to leave the answer mostly the same without being wrong. – None – 2016-12-02T00:13:52.603

@ais523 Notice that I put quote marks on both sides of the name, this is a typical string literal, its contents don't get interpreted as commands. (Also I don't remember whether it needs to be "NULL" or "LLUN" and I can't be bothered looking it up) – user253751 – 2016-12-02T10:35:58.117

30

Brainfuck, 5 bytes

+[>+]

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

vsz

Posted 2016-12-01T02:26:28.570

Reputation: 7 963

2I'm pretty sure it's +[>+] or else it would simply stop at the first iteration. ;) – Pâris Douady – 2016-12-01T14:48:56.827

You are right, sorry for the typo. – vsz – 2016-12-01T14:55:57.283

40One of the rare times where a brainfuck solution is competitive... – FlipTack – 2016-12-01T19:00:02.423

@Flp.Tkc But it still loses. Maybe it will win someday... – NoOneIsHere – 2016-12-04T17:18:35.523

6

@SeeOneRhino : It already won once, beating all golfing languages> http://codegolf.stackexchange.com/questions/8915/write-a-program-that-uses-all-printable-non-alphanumeric-ascii-symbols/8926#8926

– vsz – 2016-12-04T17:48:08.893

22

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.

Digital Trauma

Posted 2016-12-01T02:26:28.570

Reputation: 64 644

7I was about to write the same and call it a Ruby program. – G B – 2016-12-02T06:57:45.897

1and perl, I think. – abligh – 2016-12-03T12:54:27.230

18

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.

FlipTack

Posted 2016-12-01T02:26:28.570

Reputation: 13 242

18

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

redstarcoder

Posted 2016-12-01T02:26:28.570

Reputation: 1 771

2Now I'm wondering how many other 2-dimensional languages this works in. Most of them are stack-based, after all. – None – 2016-12-01T19:15:59.377

1

Almost works in Cubix, but it requires a leading . (or any non-whitespace char) to move the 0 into the line of execution.

– ETHproductions – 2016-12-01T20:04:01.570

1

Works in Ouroboros, but not in the same way: The interpreter tries to read 0000000... as a single integer literal, and the string that it builds up is what keeps taking more memory. A program that works the way this one does would be a (pushes 10 infinitely).

– DLosc – 2016-12-02T05:48:33.853

12

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

BenGoldberg

Posted 2016-12-01T02:26:28.570

Reputation: 389

You beat me to it! And yours is three bytes shorter. – Gabriel Benamy – 2016-12-01T03:10:14.570

1It was just a matter of searching this web site for the smallest loop :). Also, I'd initially has $_.=7 in my loop, but realized if I could use x= it would run out of memory much much faster, and then ran perldoc perlvar to pick something suitable. – BenGoldberg – 2016-12-01T03:11:52.213

{$^O++;redo} is one byte shorter when ^O is a single chr(15) byte. Though it will waste memory at MUCH slower rate - 1000000000 iterations are required on Windows to waste one byte. Will work on any OS that have its name starting in Latin letter. – Oleg V. Volkov – 2016-12-05T14:05:58.047

12

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

masterX244

Posted 2016-12-01T02:26:28.570

Reputation: 3 942

well I feel a little silly for not going with the obvious now, haha. I'd venture to say this is more elegant than mine – Poke – 2016-12-01T14:11:31.340

1yeah, your code remembered me to that fact with the finalize() @poke – masterX244 – 2016-12-01T14:12:38.127

I think you could make it shorter by replacing main with a static initializer – tbodt – 2016-12-01T19:26:21.470

only works up to java6 and i only got higher versions around – masterX244 – 2016-12-01T22:03:57.480

see my 81 byte answer ;) – DepressedDaniel – 2016-12-02T03:16:36.103

2haha using the garbage collector to cause a leak! great idea :) – Mark K Cowan – 2016-12-02T12:54:19.177

Relying on finalize() is a bad idea

– None – 2016-12-02T21:27:12.087

endless loop prevents exit of program though @Snowman – masterX244 – 2016-12-02T21:28:48.627

11

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 !

zeppelin

Posted 2016-12-01T02:26:28.570

Reputation: 7 884

2Strictly speaking this is GNU sed (semicolon is not standard sed) but a newline would work just as well as the semicolon anyway. – R.. GitHub STOP HELPING ICE – 2016-12-04T01:20:39.627

10

Haskell, 23 19 bytes

main=print$sum[0..]

Print the sum of an infinite list

Angs

Posted 2016-12-01T02:26:28.570

Reputation: 4 825

This is a nice way to enforce evaluation, and it's very compact too. +1 – Esolanging Fruit – 2016-12-02T03:45:34.723

a compiler could very well run this in O(1) memory. In GHC, sum is defined as foldl (+) 0, and what's to stop the strictness analysis to kick in, to prevent the thunk blow-out? Did you run it compiled with optimizations? – Will Ness – 2016-12-04T09:51:00.857

@WillNess What could the answer be? sum won't know in advance that the list is infinite and to print the sum it must be evaluated first. And yes, I compiled it with optimizations – Angs – 2016-12-04T11:27:03.577

there wouldn't be an answer; but the calculation would run in O(1) space. Oops, strike that, because of the defaulting to Integer, the numbers are unbounded and the memory taken by the bignum current result, would indeed grow. – Will Ness – 2016-12-04T13:55:42.883

1just to clarify, what I meant was that the calculation of sum xs = foldl (+) 0 xs can run in constant stack, as any imperative loop would. foldl' (+) 0 xs certainly will. So the only thing allocating memory for certain, is the bignum interim result. – Will Ness – 2016-12-05T10:47:08.960

@WillNess If that's true, this must be one of the least efficient allocators of memory ... – DepressedDaniel – 2016-12-21T02:48:06.377

@DepressedDaniel all the answers to this question are something a sufficiently smart compiler could detect and stop or optimize away. – Angs – 2016-12-21T06:49:51.837

9

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

Post Rock Garf Hunter

Posted 2016-12-01T02:26:28.570

Reputation: 55 382

3The title is misleading; the question says to "write a program which runs forever and continuously allocates memory." – NobodyNada - Reinstate Monica – 2016-12-01T02:57:00.783

Oh I did not realize you already submitted an answer when I sent mine. – Neop – 2016-12-01T03:06:35.727

1@Neop Well I didn't know you could ommit the int until I saw your's so thanks! – Post Rock Garf Hunter – 2016-12-01T03:08:27.290

Which compiler accepts this implicit int syntax? (doesn't work in MS Visual Studio) – anatolyg – 2016-12-01T10:41:51.297

@anatolyg I am using g++. – Post Rock Garf Hunter – 2016-12-01T20:00:27.880

2Not C++, just the g++ dialect of it: C++ forbids calling main; C++ requires int main... declaration. But the solution is still neat :-) – Martin Ba – 2016-12-01T22:21:43.217

1Indeed, C++ forbids calling main. – R.. GitHub STOP HELPING ICE – 2016-12-04T01:21:34.400

9

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.

DepressedDaniel

Posted 2016-12-01T02:26:28.570

Reputation: 311

Welcome to PPCG! I don't know Java very well; what would happen if you just did x+=x;? – ETHproductions – 2016-12-02T04:07:45.857

you can shave a semicolon off by putting the x+=x.intern() behind the last semicolon of the for loop – masterX244 – 2016-12-02T09:42:58.910

Nice answer. I knew there had to be something with string interning but I was pretty happy with Unsafe and finalize that I stopped looking, haha. Originally this question specified "memory leak" which is why I didn't just do a string concat answer. – Poke – 2016-12-02T14:09:47.033

If your answer depends on a specific implementation of Java, and wouldn't necessarily be portable to all Java implementations, you can place the information in the title (e.g. # Java (HotSpot), 71 bytes). That way, you don't need to worry about the solution potentially cheating; implementation-specific programs are common not just in golfing, but in the wider world of programming too, and as long as you're aware of what you're doing may sometimes be more appropriate than a portable program for, say, a one-off script. – None – 2016-12-02T16:30:51.403

for(String x="1";;x+=x); to save 1 byte. – Olivier Grégoire – 2016-12-02T18:21:44.187

1humm... x+=x; doesn't exhaust the whole memory. With 64 GB, I get an StringIndexOutOfBoundsException, not an OOM. With .intern() I still get the OOM. – Olivier Grégoire – 2016-12-02T18:30:34.653

couldn't you save a lot of space by replacing main with a static initializer? – tbodt – 2016-12-03T01:37:40.143

@tbodt That just results in a "Main method not found in class" runtime error. – DepressedDaniel – 2016-12-03T07:41:25.200

I think it works on old versions of java (like java 6), you could specify that the program only works on java 6 – tbodt – 2016-12-03T18:14:31.190

@tbodt Don't have an easy way to test the claim that it works on java 6. – DepressedDaniel – 2016-12-03T18:30:49.690

I'm going to dig up an old version of the jdk and test this when I have time... – tbodt – 2016-12-04T04:05:49.850

interesting, infinite loops aren't allowed in static initializers. so it doesn't really matter... – tbodt – 2016-12-04T04:41:53.383

@tbodt What about class A{static{for(String x="1";(x+=x.intern())==x;);}}? – DepressedDaniel – 2016-12-04T04:55:41.300

8

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

Brad Gilbert b2gills

Posted 2016-12-01T02:26:28.570

Reputation: 12 713

8

///, 7 bytes

/a/aa/a

Constantly replace a with aa, ad nauseum.

steenbergh

Posted 2016-12-01T02:26:28.570

Reputation: 7 772

12*aad naauseum – timothymh – 2016-12-02T06:32:45.813

1>

  • ad nauseam => aad naauseaam
  • < – Aaron – 2016-12-02T12:30:03.673

    What about //a/? That seems to forever replace `` (nothing) by a, but not sure if this is exactly specified. – Cedric Reichenbach – 2016-12-02T12:40:10.993

    6

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

    artificialnull

    Posted 2016-12-01T02:26:28.570

    Reputation: 481

    The title implies that the memory should be leaked. But this doesn't actually leak memory. The author should probably clarify. – Post Rock Garf Hunter – 2016-12-01T03:50:48.763

    6

    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.

    Harald Korneliussen

    Posted 2016-12-01T02:26:28.570

    Reputation: 430

    6

    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.

    Harry

    Posted 2016-12-01T02:26:28.570

    Reputation: 1 189

    6

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

    asmeurer

    Posted 2016-12-01T02:26:28.570

    Reputation: 161

    5

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

    Jonathan Allan

    Posted 2016-12-01T02:26:28.570

    Reputation: 67 804

    If I understand the rules correctly, ‘ß should be plenty. – Dennis – 2016-12-01T03:45:31.753

    Does that really "continuously allocate memory" (thinking about Python keeping constant allocation for small ints). – Jonathan Allan – 2016-12-01T03:50:16.633

    1Fair enough. should still fit the bill though. – Dennis – 2016-12-01T03:52:43.460

    5

    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.

    Digital Trauma

    Posted 2016-12-01T02:26:28.570

    Reputation: 64 644

    With malloc, you are not directly writing in the memory since malloc does not initialise anything. The memory is only allocated because malloc needs some internal storage for memory managing. So the answer isn't really standard but I guess it works everywhere anyway. – Antzi – 2016-12-02T01:43:02.607

    @Antzi Yes. However, I think this still works though because even though the user memory might not actually be allocated before it is written to, each malloc()ed block must still have its own real allocated space. This works on macOS and Ubuntu. – Digital Trauma – 2016-12-02T01:48:42.867

    The condition in the question of each page being written to is rather meaningless; even if you want to assume an OS does not do proper commit accounting, regardless of implementation details there is necessarily a nonzero amount of bookkeeping needed per allocation. Whether it is adjacent to the allocation (causing pages to be touched) or not, it will eventually consume arbitrarily amounts of memory for bookkeeping with (necessarily) nonzero data. – R.. GitHub STOP HELPING ICE – 2016-12-04T01:26:04.917

    You could get it one byte smaller as main(){main(malloc(9));}, but in order not to stack overflow, it needs tail call optimization, and gcc doesn't seem to want to do that on main... – R.. GitHub STOP HELPING ICE – 2016-12-04T01:34:22.320

    If you replace malloc(9) with calloc(9,9) then there will be enough memory allocated for 9 instances of a 9-byte block (so between 81 and 144 bytes, depending on alignment. However, and more importantly, calloc() will zero-fill the block of memory, forcing the underlying OS to allocate storage to it. – CSM – 2016-12-04T13:13:10.357

    5

    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.

    Poke

    Posted 2016-12-01T02:26:28.570

    Reputation: 3 075

    1Was wondering if I'd see Java here. – Magic Octopus Urn – 2016-12-01T14:59:15.663

    Doesn't the first one only work if the garbage collector is running in a separate thread? – tbodt – 2016-12-01T19:26:46.737

    @tbodt yes but i don't believe this is ever not the case. Garbage collection happens in a daemon thread called garbage collector – Poke – 2016-12-01T20:04:34.660

    @Poke is that guaranteed? if not the answer is still fine, but you should clarify that it only works if the garbage collector runs in its own thread – tbodt – 2016-12-01T20:05:55.370

    @tbodt I think so but I'm not certain, honestly. – Poke – 2016-12-01T20:16:27.853

    see my 81 byte answer ;) – DepressedDaniel – 2016-12-02T03:17:09.027

    5

    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.

    Laikoni

    Posted 2016-12-01T02:26:28.570

    Reputation: 23 676

    When compiled, the runtime detects the loop and breaks execution – Angs – 2016-12-01T09:41:54.917

    @Angs I compiled with ghc on windows and it keeps happily allocating memory ... I stopped it at 3GB. – Laikoni – 2016-12-01T13:41:04.057

    Using f x=f x works too, right? (−2 bytes) – wchargin – 2016-12-03T16:35:43.953

    @wchargin I don't think so, f x=f x produces an infinite loop, but without allocating new memory. – Laikoni – 2016-12-03T17:58:40.953

    Nice, causing the memory blow-out by the bignum calculations! f!x=x*f(x*x) should make it optimizations-proof. – Will Ness – 2016-12-04T13:58:35.300

    5

    Haskell (using ghc 8.0.1), 11 bytes

    m@main=m>>m
    

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

    nimi

    Posted 2016-12-01T02:26:28.570

    Reputation: 34 639

    Does this allocate on the heap or the stack? (I can believe either; it may well depend on the Haskell compiler in uses.) – None – 2016-12-01T19:20:15.467

    1

    @ais523: it depends. Haskell has no call stack. The run time system RTS has a memory area for pattern matching which is also called "stack". This stack is allocated on the heap. Honestly, I don't know what's going on here, because the program fails with Stack space overflow: current size 33624 bytes. 33k seems quite low in contrast to the 6G of total memory that the OS is reporting.

    – nimi – 2016-12-01T20:56:05.797

    1

    @ais523: there seems to be a bug in the memory information of the ghc error message, so it's hard to tell what exactly happens.

    – nimi – 2016-12-01T23:26:58.327

    Compiled on GHC 7.10.3 on Ubuntu, this seems takes a constant amount of memory even when optimizations are disabled – Angs – 2016-12-02T05:28:25.490

    @Angs: hmm, I use ghc 8.0.1 on MacOS. I'll edit this in. – nimi – 2016-12-02T05:52:40.690

    5

    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.

    faubi

    Posted 2016-12-01T02:26:28.570

    Reputation: 2 599

    Wait, so this would exponentially allocate the memory if it could run in parallel? – HyperNeutrino – 2016-12-02T02:14:54.787

    5

    Perl, 4 bytes

    do$0
    

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

    primo

    Posted 2016-12-01T02:26:28.570

    Reputation: 30 891

    Nice and short, though it doesn't waste memory quickly as mine. – BenGoldberg – 2016-12-17T18:22:51.540

    4

    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.

    Winny

    Posted 2016-12-01T02:26:28.570

    Reputation: 1 120

    Can you explain how it works? – tbodt – 2016-12-01T17:46:23.057

    1oh, so it's defining l as a function that does non-tailcall recursion. i'd say it counts. – tbodt – 2016-12-01T19:23:00.360

    @tbodt yes you're right on the money – Winny – 2016-12-01T21:54:02.747

    4

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

    Lmis

    Posted 2016-12-01T02:26:28.570

    Reputation: 421

    1On your 2nd example with ES6, couldn't you just do f=_=>f();f() ? 12 bytes – bitten – 2016-12-01T11:00:44.570

    @bitten I am not sure. If it counts to blow the call stack, then that one without proper tail calls would be the way to go. With TCO, I don't think there would be any memory leaked, would there? – Lmis – 2016-12-01T11:09:53.717

    both blow the call stack for me. i'm not really familiar with tail calls so i can't comment on that. – bitten – 2016-12-01T11:13:37.670

    1ah i see, i wasn't sure how yours was leaking memory – bitten – 2016-12-01T12:19:04.143

    1You could remove a=0. First iteration would result in a=[undefined] – Florent – 2016-12-02T15:47:02.727

    @Florent I think that should throw a ReferenceError as a is not declared (i.e. var a is missing), shouldn't it? – Lmis – 2016-12-05T09:16:25.670

    @Lmis only in strict mode. – Florent – 2016-12-05T09:44:06.957

    4

    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.
    

    Magic Octopus Urn

    Posted 2016-12-01T02:26:28.570

    Reputation: 19 422

    Very thorough! Nice. – timothymh – 2016-12-02T06:34:24.777

    4

    Ruby, 11 bytes

    loop{$*<<9}
    

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

    daniero

    Posted 2016-12-01T02:26:28.570

    Reputation: 17 193

    3

    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.

    Noelkd

    Posted 2016-12-01T02:26:28.570

    Reputation: 1 025

    1Can you do a+=a,? – Cyoce – 2016-12-02T01:23:52.033

    No need for a function, here's my golf of it

    – FlipTack – 2016-12-02T07:25:21.913

    @Flp.Tkc the question was changed after I wrote this answer I would have done what you did (+- couple of characters) if it was in its current format. – Noelkd – 2016-12-02T09:49:08.943

    3

    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.

    FlipTack

    Posted 2016-12-01T02:26:28.570

    Reputation: 13 242

    I don't think the REPL is allowed. – Pavel – 2016-12-01T20:44:56.450

    @Pavel http://meta.codegolf.stackexchange.com/a/7844/60919

    – FlipTack – 2016-12-01T22:04:16.223

    3

    PHP, 14 13 bytes

    Saved a byte thanks to Alex Howansky

    while($a.=1);
    

    Indefinitely builds a string of 111111111111...

    MonkeyZeus

    Posted 2016-12-01T02:26:28.570

    Reputation: 461

    Which bizarre quirk of php does this exploit? – tbodt – 2016-12-01T21:35:14.530

    @tbodt $a[]=1 evaluates to something truthy so the while() loop equates to while(true) and just keeps looping and adding elements to the $a array. Not sure if this can be classified as a quirk though. Is identifying a quirk a requirement of your question? Would you like me to deconstruct my answer into multiple lines? – MonkeyZeus – 2016-12-01T21:38:49.880

    @tbodt Try it out at http://sandbox.onlinephpfunctions.com/

    – MonkeyZeus – 2016-12-01T21:52:20.370

    2You can chop a byte with while($a.=1); -- just build a huge string versus a huge array. – Alex Howansky – 2016-12-01T22:11:08.783

    while($a.=1); indefinetely adds characters to a string. – Titus – 2016-12-01T23:08:51.587

    Didn't know that $a[] = x adds an element to an array in PHP. I would classify that as a bizarre quirk since I don't know of any other language that does that. – tbodt – 2016-12-01T23:50:37.093

    Also note that $a is never declared, and starts with a value of NULL. By assigning a value with square brackets $a[]=, you're implicitly casting NULL to an empty array, and then appending a value. – whitehat101 – 2016-12-02T03:15:37.593

    @tbodt It's actually a well-known language construct and PHP is definitely full of fun little surprises :-) – MonkeyZeus – 2016-12-02T20:19:24.413

    3

    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

    harold

    Posted 2016-12-01T02:26:28.570

    Reputation: 1 199

    3

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

    Eric Towers

    Posted 2016-12-01T02:26:28.570

    Reputation: 706

    2

    BASH, 2 bytes

    $0
    

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

    Ipor Sircer

    Posted 2016-12-01T02:26:28.570

    Reputation: 333

    5This starts new processes repeatedly, instead of allocating memory in a single process, so I would say it doesn't count. – tbodt – 2016-12-01T17:10:04.160

    1It could theoretically work on an operating system where processes share the heap with each other (some variants of uclinux, perhaps; DOS has a shared heap in 16-bit mode but I don't know that it has a bash implementation)? I don't think this can be valid without specifying an OS where it works, though. (Also, the process limit may be hit before the memory limit is.) – None – 2016-12-01T18:43:12.710

    I think $0|$0 works, but it's longer. – Pavel – 2016-12-01T20:46:12.030

    $0 $@$$& if you really wanted to kill your system, whilst not using compressed RAM. – Stan Strum – 2018-01-29T20:50:01.437

    2

    Microscript II, 3 bytes

    1[s
    

    Rough translation:

    x=1
    while x
      push x
    

    SuperJedi224

    Posted 2016-12-01T02:26:28.570

    Reputation: 11 342

    2

    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
    

    Paŭlo Ebermann

    Posted 2016-12-01T02:26:28.570

    Reputation: 1 010

    2

    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.

    mbomb007

    Posted 2016-12-01T02:26:28.570

    Reputation: 21 944

    2

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

    milk

    Posted 2016-12-01T02:26:28.570

    Reputation: 3 043

    2

    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.

    user3490

    Posted 2016-12-01T02:26:28.570

    Reputation: 809

    2

    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.

    Mego

    Posted 2016-12-01T02:26:28.570

    Reputation: 32 998

    2

    Labyrinth, 1 byte

    _
    

    This keeps pushing a 0 to the stack.

    Stefnotch

    Posted 2016-12-01T02:26:28.570

    Reputation: 607

    2

    Brain-Flak, 10 bytes

    (()){(())}
    

    Try it online!

    Pavel

    Posted 2016-12-01T02:26:28.570

    Reputation: 8 585

    1In the Ruby Brain-Flak interpreter just (()){()} Will actually work. This is because the Brain-Flak interpreter stores a unbounded variable called @current_value that is incremented by (). Each run of the loop will do nothing visible but will increment that value. As the value grows the program will allocate more and more memory. – Post Rock Garf Hunter – 2017-02-15T15:02:39.990

    2

    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.

    James

    Posted 2016-12-01T02:26:28.570

    Reputation: 54 537

    2

    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

    TheLethalCoder

    Posted 2016-12-01T02:26:28.570

    Reputation: 6 930

    1

    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.

    FlipTack

    Posted 2016-12-01T02:26:28.570

    Reputation: 13 242

    1

    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.

    DLosc

    Posted 2016-12-01T02:26:28.570

    Reputation: 21 213

    1

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

    user41805

    Posted 2016-12-01T02:26:28.570

    Reputation: 16 320

    1

    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.

    user18932

    Posted 2016-12-01T02:26:28.570

    Reputation:

    You must have missed by answer based on explicitly interning Strings. Also, you can put just l.add(l) in the for loop to save a lot of bytes, and create the loop in the for initializer to get down to 103 bytes. – DepressedDaniel – 2016-12-02T23:04:03.073

    @DepressedDaniel I must have missed your answer. I saw several Java answers but they were all focused on the garbage collector. And you are right - by using raw types I can make this more efficient. I'll take a look later. Thanks for the tips. – None – 2016-12-03T00:06:40.360

    You can replace s+=' ';l.add(s); with l.add(s+=' '); – Cyoce – 2017-03-16T20:21:36.530

    1

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

    Booga Roo

    Posted 2016-12-01T02:26:28.570

    Reputation: 141

    Since .NET strings are just char[] in the background, you could use an array and do for(){$i+=,1} to save a byte. – AdmBorkBork – 2016-12-05T19:16:18.727

    1

    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.

    Adám

    Posted 2016-12-01T02:26:28.570

    Reputation: 37 779

    I've already learned Lisp and Prolog, I should learn APL now – tbodt – 2016-12-08T16:38:39.137

    @tbodt Can I help you get started? – Adám – 2016-12-08T16:44:35.130

    sure, got any nice links? – tbodt – 2016-12-08T16:46:01.957

    @tbodt First, get the full version of Dyalog APL, and while you wait for your license to arrive, have a look at the "Learn" tab of tryapl.org. The book Mastering Dyalog APL is a must. If you don't want to pay, you can just download the PDF for free.

    – Adám – 2016-12-08T16:55:06.387

    @tbodt Make sure to check out #onelinerwednesday and YouTube. Use Twitter, Facebook, or visit the forums or send me an email if you get stuck or have questions.

    – Adám – 2016-12-08T17:10:06.253

    1

    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.

    12Me21

    Posted 2016-12-01T02:26:28.570

    Reputation: 6 110

    The old versions of A$ probably get garbage-collected. This technically does continuously allocate memory but it would be more spectacular if it crashed eventually :) – snail_ – 2017-02-07T13:44:44.270

    There's no way to avoid SB's garbage collector, it's way too reliable. – 12Me21 – 2017-02-07T13:45:49.273

    You could PUSH an array until you get Out of memory but that would in fact be longer. – snail_ – 2017-02-07T13:46:50.150

    1

    √ å ı ¥ ® Ï Ø ¿ , 3 bytes

    (1)
    

    Explanation

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

    caird coinheringaahing

    Posted 2016-12-01T02:26:28.570

    Reputation: 13 702

    1

    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.

    Bijan

    Posted 2016-12-01T02:26:28.570

    Reputation: 781

    1

    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.

    L3viathan

    Posted 2016-12-01T02:26:28.570

    Reputation: 3 151

    1

    Aceto, 2 bytes, non-competing

    Non-competing because Aceto postdates the challenge.

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

    L3viathan

    Posted 2016-12-01T02:26:28.570

    Reputation: 3 151

    0

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

    F. George

    Posted 2016-12-01T02:26:28.570

    Reputation: 317

    0

    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.

    pmbanka

    Posted 2016-12-01T02:26:28.570

    Reputation: 171

    Could this be golfed to let rec f x=1::f(x)? – Peter Taylor – 2016-12-15T10:52:58.983

    @PeterTaylor your code results in StackOverflowException, which (if I understand correctly) is not a desired outcome for this challenge. Curiously, the version I posted seems to be tail-recursive optimized. – pmbanka – 2016-12-15T12:18:26.740

    As a side note - if StackOverflowException is a valid option, then it can be even shorter: let rec f()=1::f(). But I think it is way more fun to just watch the FSI process to eat more and more memory :) – pmbanka – 2016-12-15T12:28:05.377

    0

    BotEngine, 2x3=6

    ve<
    >e^
    

    Rough translation:

    forever:
      enqueue 'e'
      enqueue 'e'
    

    SuperJedi224

    Posted 2016-12-01T02:26:28.570

    Reputation: 11 342

    I don’t know what this language even is, but it looks 2D — wouldn’t >e< work (or >e if there’s wrapping?) – Lynn – 2016-12-08T15:22:25.173

    Unfortunately, no. I believe both would produce an error (missing argument on the e instruction), and the language doesn't have wrapping. – SuperJedi224 – 2016-12-08T17:20:06.730

    0

    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.

    Aron_dc

    Posted 2016-12-01T02:26:28.570

    Reputation: 101

    1

    It might be shorter to use the fully qualified name of the class instead of importing. (see http://codegolf.stackexchange.com/a/16100/10801 and all other answers at that page. useful tips en masse there)

    – masterX244 – 2016-12-05T13:58:28.323

    0

    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 :'(!

    Filip Dupanović

    Posted 2016-12-01T02:26:28.570

    Reputation: 101

    0

    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.

    Shaun Bebbers

    Posted 2016-12-01T02:26:28.570

    Reputation: 1 814

    0

    C#, 28 bytes

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

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

    Metoniem

    Posted 2016-12-01T02:26:28.570

    Reputation: 387

    0

    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.

    Shaun Bebbers

    Posted 2016-12-01T02:26:28.570

    Reputation: 1 814

    Actually one should be able to 1 GOSUB 1 - why didn't I think of that. – Shaun Bebbers – 2017-04-05T18:42:37.677

    0

    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;}}
    

    Johan du Toit

    Posted 2016-12-01T02:26:28.570

    Reputation: 1 524

    0

    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.

    David

    Posted 2016-12-01T02:26:28.570

    Reputation: 1

    0

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

    Ephphatha

    Posted 2016-12-01T02:26:28.570

    Reputation: 581

    0

    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
    

    MD XF

    Posted 2016-12-01T02:26:28.570

    Reputation: 11 605