Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Your task is to write code that will leak at least one byte of memory in as few bytes as possible. The memory must leaked not just allocated.

Leaked memory is memory that the program allocates but looses the ability to access before it can deallocate the memory properly. For most high level languages this memory has to be allocated on the heap.

An example in C++ would be the following program:

int main{new int;}

This makes a new int on the heap without a pointer to it. This memory is instantly leaked because we have no way of accessing it.

Here is what a leak summary from Valgrind might look like:

LEAK SUMMARY:
   definitely lost: 4 bytes in 1 blocks
   indirectly lost: 0 bytes in 0 blocks
     possibly lost: 0 bytes in 0 blocks
   still reachable: 0 bytes in 0 blocks
        suppressed: 0 bytes in 0 blocks

Many languages have a memory debugger (such as Valgrind) if you can you should include output from such a debugger to confirm that you have leaked memory.

The goal is to minimize the number of bytes in your source.

share|improve this question
1  
Perhaps you could have different ranges of amount leaked and depending on how much you leak you lose x% of your byte count – Christopher Peart 2 days ago
8  
@ChristopherPeart For one I am not a fan of bonuses on challenges and for two as you have already shown it is very easy to leak unbounded memory. – Wheat Wizard 2 days ago
1  
Related. Not a duplicate, though, because most answers to that question form an infinite reachable structure in memory rather than actually leaking memory. – ais523 2 days ago
2  
what is the idea? That the mem cannot be freed? I guess this would require native execution for garbage collected languages or exploiting bugs. – akostadinov 2 days ago
2  
I see how languages designed for golfing fail miserably on this one ... – Kh40tiK yesterday

27 Answers 27

C, 48 31 22 bytes

Warning: Don't run this too many times.

Thanks to Dennis for lots of help/ideas!

f(k){shmget(k,1,512);}

This goes one step further. shmget allocates shared memory that isn't deallocated when the program ends. It uses a key to identify the memory, so we use an uninitialized int. This is technically undefined behaviour, but practically it means that we use the value that is just above the top of the stack when this is called. This will get written over the next time that anything is added to the stack, so we will loose the key.


The only case that this doesn't work is if you can figure out what was on the stack before. For an extra 19 bytes you can avoid this problem:

f(){srand(time(0));shmget(rand(),1,512);}

Or, for 26 bytes:

main(k){shmget(&k,1,512);}

But with this one, the memory is leaked after the program exits. While running the program has access to the memory which is against the rules, but after the program terminates we loose access to the key and the memory is still allocated. This requires address space layout randomisation (ASLR), otherwise &k will always be the same. Nowadays ASLR is typically on by default.


Verification:

You can use ipcs -m to see what shared memory exists on your system. I removed pre-existing entries for clarity:

$ cat leakMem.c 
f(k){shmget(k,1,512);}
int main(){f();}     
$ gcc leakMem.c -o leakMem
leakMem.c:1:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
 f(k){shmget(k,1,512);}
 ^
leakMem.c: In function ‘f’:
leakMem.c:1:1: warning: type of ‘k’ defaults to ‘int’ [-Wimplicit-int]
leakMem.c:1:6: warning: implicit declaration of function ‘shmget’ [-Wimplicit-function-declaration]
 f(k){shmget(k,1,512);}
ppcg:ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      


$ ./leakMem 

$ ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      

0x0000007b 3375157    Riley      0          1          0  
share|improve this answer
1  
@AndrewSavinykh Theoretically, the shmid could have been stored in a file and a program could attach to it in the future. This is how unix shared memory works... – tbodt 2 days ago
1  
@AndrewSavinykh Shared memory basically becomes a resource that the OS can give to other processes. It is similar to a file that lives in RAM and any process that knows the name (key) has access to it until it is deleted. Imagine a process that calculates a number and stores it in memory and exits before the process that reads the data connects to the shared memory. In this case, if the OS frees the memory then the second process can't get it. – Riley 2 days ago
13  
Thank you for posting this. I just protected TIO against shared memory leaks. – Dennis 2 days ago
2  
@Dennis That's why I didn't post a TIO link. I didn't know if it was protected or not. – Riley 2 days ago
1  
I like how you use the word problem to describe the scenario where the program leaks less memory than intended. – kasperd yesterday

Perl (5.22.2), 0 bytes

Try it online!

I knew there'd be some language out there that leaked memory on an empty program. I was expecting it to be an esolang, but turns out that perl leaks memory on any program. (I'm assuming that this is intentional, because freeing memory if you know you're going to exit anyway just wastes time; as such, the common recommendation nowadays is to just leak any remaining memory once you're in your program's exit routines.)

Verification

$ echo -n | valgrind perl
…snip…
==18517== 
==18517== LEAK SUMMARY:
==18517==    definitely lost: 8,134 bytes in 15 blocks
==18517==    indirectly lost: 154,523 bytes in 713 blocks
==18517==      possibly lost: 0 bytes in 0 blocks
==18517==    still reachable: 0 bytes in 0 blocks
==18517==         suppressed: 0 bytes in 0 blocks
==18517== 
==18517== For counts of detected and suppressed errors, rerun with: -v
==18517== ERROR SUMMARY: 15 errors from 15 contexts (suppressed: 0 from 0)
share|improve this answer
    
Is there any way to get the valgrind output on TIO? The empty program itself isn't very enlightening :P – CAD97 2 days ago
1  
@CAD97: Not as far as I know (TIO doesn't have valgrind installed), but the TIO link at least shows what the program's "main" functionality is (i.e. nothing). The links are also generally useful for things like formatting the post, giving a machine-readable version of the program, etc. (although arguably none of that is useful here). The best example of a pointless TIO link is probably this one (which caught a lot of attention at the time). – ais523 2 days ago
7  
I liked the Unlambda answer, but this one is (IMHO) too much of a stretch, as it is obviously the interpreter itself which leaks the memory, i.e. I get ` definitely lost: 7,742 bytes in 14 blocks` when I run perl --version on my machine, despite it never gets to running any program, at all. – zeppelin 2 days ago
5  
@zeppelin: Agreed, but according to our rules, it's the implementation that defines the language, thus if the implementation leaks memory, all programs in the language leak memory. I'm not necessarily sure I agree with that rule, but at this point it's too entrenched to really be able to change. – ais523 2 days ago
5  
This also works in Node JS. – Dennis yesterday

Unlambda (c-refcnt/unlambda), 1 byte

i

Try it online!

This is really a challenge about finding a pre-existing interpreter which leaks memory on very simple programs. In this case, I used Unlambda. There's more than one official Unlambda interpreter, but c-refcnt is one of the easiest to build, and it has the useful property here that it leaks memory when a program runs successfully. So all I needed to give here was the simplest possible legal Unlambda program, a no-op. (Note that the empty program doesn't work here; the memory is still reachable at the time the interpreter crashes.)

Verification

$ wget ftp://ftp.madore.org/pub/madore/unlambda/unlambda-2.0.0.tar.gz
…snip…
2017-02-18 18:11:08 (975 KB/s) - ‘unlambda-2.0.0.tar.gz’ saved [492894]
$ tar xf unlambda-2.0.0.tar.gz 
$ cd unlambda-2.0.0/c-refcnt/
$ gcc unlambda.c
$ echo -n i | valgrind ./a.out /dev/stdin
…snip…
==3417== LEAK SUMMARY:
==3417==    definitely lost: 40 bytes in 1 blocks
==3417==    indirectly lost: 0 bytes in 0 blocks
==3417==      possibly lost: 0 bytes in 0 blocks
==3417==    still reachable: 0 bytes in 0 blocks
==3417==         suppressed: 0 bytes in 0 blocks
==3417== 
==3417== For counts of detected and suppressed errors, rerun with: -v
==3417== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
share|improve this answer

TI-Basic, 12 bytes

While 1
Goto A
End
Lbl A
Pause 

"... a memory leak is where you use a Goto/Lbl within a loop or If conditional (anything that has an End command) to jump out of that control structure before the End command is reached... " (more)

share|improve this answer
1  
Wow, I think I remember this. I kept jumping out of my loops in my old basic programs and noticed how my TI-84+ got slower and slower... – Ray Koopa 2 days ago
1  
Yep, most of us know the feeling ;) @RayKoopa – Timtech 2 days ago
4  
+1 for Ti Basic. I spent most of my 9th grade year programming those things. – Markasoftware 2 days ago
    
Do you need Pause at the end? You could save 2 bytes. – kamoroso94 2 days ago
    
@kamoroso94 I think so, because "If a program is ended the leak is cleared and will cause no further issues", so it is to stop the program from ending. – Timtech yesterday

C (gcc), 15 bytes

f(){malloc(1);}

Verification

$ cat leak.c
f(){malloc(1);}
main(){f();}
$ gcc -g -o leak leak.c
leak.c: In function ‘f’:
leak.c:1:5: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
 f(){malloc(1);}
     ^
$ valgrind --leak-check=full ./leak
==32091== Memcheck, a memory error detector
==32091== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==32091== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==32091== Command: ./leak
==32091==
==32091==
==32091== HEAP SUMMARY:
==32091==     in use at exit: 1 bytes in 1 blocks
==32091==   total heap usage: 1 allocs, 0 frees, 1 bytes allocated
==32091==
==32091== 1 bytes in 1 blocks are definitely lost in loss record 1 of 1
==32091==    at 0x4C29110: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==32091==    by 0x40056A: f (leak.c:1)
==32091==    by 0x40057A: main (leak.c:2)
==32091==
==32091== LEAK SUMMARY:
==32091==    definitely lost: 1 bytes in 1 blocks
==32091==    indirectly lost: 0 bytes in 0 blocks
==32091==      possibly lost: 0 bytes in 0 blocks
==32091==    still reachable: 0 bytes in 0 blocks
==32091==         suppressed: 0 bytes in 0 blocks
==32091==
==32091== For counts of detected and suppressed errors, rerun with: -v
==32091== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
share|improve this answer

Rust, 52 bytes

extern{fn malloc(_:u8);}fn main(){unsafe{malloc(9)}}

Allocates some bytes with the system malloc. This assumes the wrong ABI is acceptable.


Rust (in theory), 38 bytes

fn main(){Box::into_raw(Box::new(1));}

We allocate memory on the heap, extract a raw pointer, and then just ignore it, effectively leaking it. (Box::into_raw is shorter then std::mem::forget).

However, Rust by default uses jemalloc, which valgrind can't detect any leakage. We could switch to the system allocator but that adds 50 bytes and requires nightly. Thanks so much for memory safety.


Output of the first program:

==10228== Memcheck, a memory error detector
==10228== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==10228== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info
==10228== Command: ./1
==10228== 
==10228== 
==10228== HEAP SUMMARY:
==10228==     in use at exit: 9 bytes in 1 blocks
==10228==   total heap usage: 7 allocs, 6 frees, 2,009 bytes allocated
==10228== 
==10228== LEAK SUMMARY:
==10228==    definitely lost: 9 bytes in 1 blocks
==10228==    indirectly lost: 0 bytes in 0 blocks
==10228==      possibly lost: 0 bytes in 0 blocks
==10228==    still reachable: 0 bytes in 0 blocks
==10228==         suppressed: 0 bytes in 0 blocks
==10228== Rerun with --leak-check=full to see details of leaked memory
==10228== 
==10228== For counts of detected and suppressed errors, rerun with: -v
==10228== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
share|improve this answer

Javascript, 14 bytes

Golfed

setInterval(0)

Registers an empty interval handler with a default delay, discarding the resulting timer id (making it impossible to cancel).

enter image description here

I've used a non-default interval, to create several million timers, to illustrate the leak, as using a default interval eats CPU like mad.

share|improve this answer
2  
Haha I love that you've typed 'Golfed', makes me curious about the ungolfed version – Martijn 19 hours ago
3  
it might look like this if(window && window.setInterval && typeof window.setInterval === 'function') { window.setInterval(0); } – Tschallacka 18 hours ago
    
@Martijn Believe it or not, but I actually did golfed it a bit :) The proper syntax for setInterval is setInterval(func|string, delay[, param1, param2, ...]);, and both func and delay are required parameters, so setInterval(0) abuses them both. – zeppelin 18 hours ago
1  
Actually, this is not impossible to cancel: interval (and timeout) ID's are numbered sequentially, so it's fairly easy to cancel the thing just by calling clearInterval with an incrementing ID until your interval is gone. For example: for(let i=0;i<1e5;i++){try{clearInterval(i);}catch(ex){}} – user2428118 11 hours ago
    
Not wholly unreachable: The interval id can be guessed in multiple ways: Just plain brute force: for (var i = 0; i++; i<100) { clearInterval(i) }, or more 'elegantly': var i = setInterval(); clearInterval(i); clearInterval(i-1) since it is just an incremented integer. – Wizek 11 hours ago

Python, 23 bytes

property([]).__init__()

property.__init__ leaks references to the property's old fget, fset, fdel, and __doc__ if you call it on an already-initialized property instance. This is a bug, not currently fixed in any Python version. (Also, yes, property([]) is a thing you can do.)

share|improve this answer

C#, 34 bytes

class L{~L(){for(;;)new L();}}

This solution does not require the Heap. It just needs a real hard working GC (Garbage Collector).

Essentially it turns the GC into it's own enemy.

Explanation

Whenever the destructor is called, It creates new instances of this evil class as long as the timeout runs out and tells the GC to just ditch that object without waiting for the destructor to finish. By then thousands of new instances have been created.

The "evilness" of this is, the harder the GC is working, the more this will blow up in your face.

Disclaimer: Your GC may be smarter than mine. Other circumstances in the program may cause the GC to ignore the first object or it's destructor. In these cases this will not blow up. But in many variations it will. Adding a few bytes here and there might ensure a leak for every possible circumstanceces. Well except for the power switch maybe.

Test

Here is a test suit:

using System;
using System.Threading;
using System.Diagnostics;
class LeakTest {
    public static void Main() {
        SpawnLeakage();
        Console.WriteLine("{0}-: Objects may be freed now", DateTime.Now);
        // any managed object created in SpawbLeakage 
        //  is no longer accessible
        // The GC should take care of them

        // Now let's see
        MonitorGC();
    }
    public static void SpawnLeakage() {
        Console.WriteLine("{0}-: Creating 'leakage' object", DateTime.Now);
        L l = new L();
    }
    public static void MonitorGC() {
        while(true) {
            int top = Console.CursorTop;
            int left = Console.CursorLeft;
            Console.WriteLine(
                "{0}-: Total managed memory: {1} bytes",
                DateTime.Now,
                GC.GetTotalMemory(false)
            );
            Console.SetCursorPosition(left, top);
        }
    }
}

Output after 10 minutes:

2/19/2017 2:12:18 PM-: Creating 'leakage' object
2/19/2017 2:12:18 PM-: Objects may be freed now
2/19/2017 2:22:36 PM-: Total managed memory: 2684476624 bytes

That's 2 684 476 624 bytes. The Total WorkingSet of the process was about 4.8 GB

This answer has been inspired by Eric Lippert's wonderful article: When everything you know is wrong

share|improve this answer
    
This is fascinating. Does the garbage collector "Forget" that some things exist and lose track of them because of this? I dont know much about c#. Also now I am wondering, what is the difference between a bomb and a leak? I imagine a similar fiasco could be created by calling a constructor from inside of a constructor, or having an infinite recursing function that never stops, although technically the system never loses track of those references, it just runs out of space... – don bright yesterday
1  
A constructor within a constructor would cause a stack overflow. But the destructor of an instance gets called in a flat hierarchy. The GC actually never loses track of the objects. Just whenever it tries to destroy them it unwittingly create new objects. User code on the other hand has no access to said objects. Also the mentioned inconsistencies may arise since the GC may decide to destroy an object without calling its destructor. – MrPaulch yesterday
    
Wouldn't the challenge be complete by just using class L{~L(){new L();}}? AFAIK the for(;;) only makes it leak memory faster, right? – BgrWorker yesterday
    
Sadly, no. Since for each destroyed object only one new instance is going to be created, which then again is inaccessible and marked for destruction. Repeat. Only ever one object will be pending for destruction. No increasing population. – MrPaulch yesterday
    
@MrPaulch well, the challenge only asks you to leak one byte, and according to the very interesting article you linked at the bottom, when the program ends finalizers will eventually timeout and the last created object will remain allocated. – BgrWorker yesterday

Forth, 6 bytes

Golfed

s" " *

Allocates an empty string with s" ", leaving it's address and length (0) on the stack, then multiplies them (resulting in a memory address being lost).

Valgrind

%valgrind --leak-check=full gforth -e 's" " * bye'
...
==12788== HEAP SUMMARY:
==12788==     in use at exit: 223,855 bytes in 3,129 blocks
==12788==   total heap usage: 7,289 allocs, 4,160 frees, 552,500 bytes allocated
==12788== 
==12788== 1 bytes in 1 blocks are definitely lost in loss record 1 of 22
==12788==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12788==    by 0x406E39: gforth_engine (in /usr/bin/gforth-0.7.0)
==12788==    by 0x41156A: gforth_go (in /usr/bin/gforth-0.7.0)
==12788==    by 0x403F9A: main (in /usr/bin/gforth-0.7.0)
==12788== 
...
==12818== LEAK SUMMARY:
==12818==    definitely lost: 1 bytes in 1 blocks
==12818==    indirectly lost: 0 bytes in 0 blocks
share|improve this answer

8086 ASM, 3 bytes

This examples assumes that a C runtime is linked in.

jmp _malloc

this assembles to e9 XX XX where XX XX is the relative address of _malloc

This invokes malloc to allocate an unpredictable amount of memory and then immediately returns, terminating the processes. On some operating systems like DOS, the memory might not be reclaimable at all until the system is rebooted!

share|improve this answer

Java, 10 bytes

Finally, a competitive answer in Java !

Golfed

". "::trim

This is a method reference (against a string constant), which can be used like that:

Supplier<String> r = ". "::trim

A literal string ". " will be automatically added to the global interned strings pool, as maintained by the java.lang.String class, and as we immediatelly trim it, the reference to it can not be reused further in the code (unless you declare exactly the same string again).

...

A pool of strings, initially empty, is maintained privately by the class String.

All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.

...

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern--

You can turn this in a "production grade" memory leak, by adding the string to itself and then invoking the intern() method explicitly, in a loop.

share|improve this answer
2  
I considered this for C#... but I don't think it counts, because as you say you can access that memory by including another string literal. I'd also be interested to know what ("." + " ").intern() would do (if they were user input or w/e, so we discount compiler optimisations). – VisualMelon 2 days ago
    
@VisualMelon - the reference is lost, so you have to recreate the string content exactly, to be able to access it again, which is pretty much impossible to do programmatically. – zeppelin 2 days ago
1  
Indeed, the only consensus is slim at best, I'm just firmly on the "the code should compile" side. I'm still not sure I buy this solution given the wording on the question (these strings can't be freed, and they can be found in normal operating code even though it's unlikely), but I invite others to make their own judgement – VisualMelon yesterday
1  
That string isn't even inaccessible, let alone leaked. We can retrieve it at any time by interning an equal string. If this were to count, any unused global variable (private static in Java) would be a leak. That's not how memory leaks are defined. – user2357112 yesterday
1  
@user2357112 "...That string isn't even inaccessible..." That only looks obvious because you see the code. Now consider you got this method reference X() as an argument to your code, you know that it allocates (and interns) a string literal inside, but you do not know which one exactly, it might be ". " or "123" or any other string of a (generally) unknown length. Would you please demonstrate how you can still access it, or deallocate the entry in the "intern" pool it occupies? – zeppelin yesterday

go 45 bytes

package main
func main(){go func(){for{}}()}

this creates an anonymous goroutine with an infinite loop inside of it. the program can continue to run as normal, as starting the goroutine is kind of like spawning a concurrently running small thread, but the program has no way to reclaim the memory that was allocated for the goroutine. the garbage collector will never collect it either since it is still running. some people call this 'leaking a goroutine'

share|improve this answer

Swift 3, 38 bytes

New version:

class X{var x: X!};do{let x=X();x.x=x}

x has a strong reference to itself, so it will not be deallocated, leading to a memory leak.

Old version:

class X{var y:Y!}
class Y{var x:X!}
do{let x=X();let y=Y();x.y=y;y.x=x}

x contains a strong reference to y, and vice versa. Thus, neither will be deallocated, leading to a memory leak.

share|improve this answer
    
Hmm, you still can reference that memory through x and y, so this does not really look like a leak to me (unless you destroy them somehow). – zeppelin 2 days ago
    
@zeppelin The last line could be wrapped in a function to fix that – NobodyNada yesterday
    
@NobodyNada, if I were to put the last line in a do block that would fix the problem zeppelin raised right? – Dopapp yesterday
    
@Dopapp Yeah; a do would work as well. Good idea! – NobodyNada yesterday
    
It can be shortened, you don't need two classes - X can hold reference to itself: class X{var x: X!};do{let x=X();x.x=x} – Sebastian Osiński 15 hours ago

AutoIt, 39 bytes

#include<Memory.au3>
_MemGlobalAlloc(1)

Allocates one byte from the heap. Since the handle returned by _MemGlobalAlloc is discarded, there is no way to explicitly free that allocation.

share|improve this answer

Delphi (Object Pascal) - 33 bytes

Creating an object without a variable, full console program:

program;begin TObject.Create;end.

Enabling FastMM4 in the project will show the memory leak:

enter image description here

share|improve this answer

Befunge (fungi), 1 byte

$

This may be platform dependent and version dependent (I've only tested with version 1.0.4 on Windows), but fungi has historically been a very leaky interpreter. The $ (drop) command shouldn't do anything on an empty stack, but looping over this code somehow manages to leak a lot of memory very quickly. Within a matter of seconds it will have used up a couple of gigs and will crash with an "out of memory" error.

Note that it doesn't necessarily have to be a $ command - just about anything would do. It won't work with a blank source file though. There's got to be at least one operation.

share|improve this answer

Java 1.3, 23 bytes

void l(){new Thread();}

Creating a thread but not starting it. The thread is registered in the internal thread pool, but will never be started, so never ended and therefore never be a candidate for the GC. It is an unretrievable object, stuck in Java limbos.

Works only until Java 1.3 included. It's been patched afterwards. The rules of PCG mention that an entry must work consistently on at least one environment to be OK, so this entry is OK in that regards.

Testing

The following program makes sure to pollute the memory with new thread objects and show a decreasing free memory space. For the sake of leaks testing, I intensively makes the GC run.

public class Pcg110485 {

    static
    void l(){new Thread();}

    public static void main(String[] args) {

        while(true){
            l();
            System.gc();
            System.out.println(Runtime.getRuntime().freeMemory());
        }
    }
}
share|improve this answer
1  
@zeppelin Yes, here's the original bug report: bugs.java.com/view_bug.do?bug_id=4410846 – Olivier Grégoire 22 hours ago
    
Since this works only on specific Java versions, you should say "Java 3" in your header instead. – Snowman 18 hours ago
    
There's no such thing as Java 3. It's Java 1.3. There was Java 1.0, 1.1, 2, 1.3, 1.4, 5, 6, 7, 8, 9. Weird numbering, but that's how it is. – Olivier Grégoire 8 hours ago

C# - 84bytes

class P{static void Main(){System.Runtime.InteropServices.Marshal.AllocHGlobal(1);}}

This allocates exactly 1 byte of unmanaged memory, and then loses the IntPtr, which I believe is the only way to get at or free it. You can test it by stuffing it in a loop, and waiting for the application to crash (might want to add a few zeros to speed things up).

I considered System.IO.File.Create("a"); and such, but I'm not convinced that these are necessarily memory leaks, as the application itself will collect the memory, it's the OS underneath that might leak (because Close or Dispose were not called). File access stuff also requires file system permissions, and no one wants to rely on those. And it turns out this won't leak anyway, because there is nothing stopping the finaliser being called (which does free the underlying resources is possible), which the framework includes to mitigate these sorts of error of judgement (to some degree), and to confuse programmers with seemingly non-deterministic file locking (if you're a cynic). Thanks to Jon Hanna for putting me straight on this.

I am a tad disappointed that I can't find a shorter way. The .NET GC works, I can't think of any IDisposables in mscorlib that will definitely leak (and indeed they all seem to have finalisers, how annoying), I'm not aware of any other way to allocate unmanaged memory (short of PInvoke), and reflection ensures anything with a reference to it (regardless of language semantics (e.g. private members or classes with no accessors)) can be found.

share|improve this answer
1  
System.IO.File.Create("a") won't leak anything, but GC.SuppressFinalize(System.IO.File.Create("a")) will as it is explicitly asked not to run the finaliser of the FileStream produced. – Jon Hanna 2 days ago
    
@JonHanna quite right. My IDisposable paranoia seems to have got the better of me. – VisualMelon 2 days ago
    
You might have a chance to make GDI+ leak using System.Drawing.Bitmap. Don't know if it counts because it's a windows library causing the leak, not the program itself. – BgrWorker yesterday
    
@BgrWorker they no doubt have a finaliser also, and I tend to avoid external libraries in code-golf because I don't agree with the consensus on costing them: if you can find a way you're confident in, feel free to post it in your own answer! – VisualMelon 16 hours ago

Factor, 13 bytes

Factor has automatic memory management, but also gives access to some libc functionality:

1 malloc drop

Manually allocates 1 byte of memory, returns it's address, and drops it.

malloc actually registers a copy to keep track of memory leaks adn double frees, but identifying the one you leaked is not an easy task.

If you prefer to make sure you really lose that reference:

1 (malloc) drop

Testing leaks with [ 1 malloc drop ] leaks. says:

| Disposable class | Instances |                    |
| malloc-ptr       | 1         | [ List instances ] |

Testing leaks with [ 1 (malloc) drop ] leaks. says:

| Disposable class | Instances | |

Oh no! Poor factor, it's got Alzheimer now! D:

share|improve this answer

Common Lisp (SBCL only), 28 bytes

sb-alien::(make-alien int)()
  1. package::(form) is a special notation in SBCL for temporarily binding the current package while reading a form. This is used here to avoid prefixing both make-alien and int with sb-alien. I think it would be cheating to assume the current package is set to this one, because that's not the case at startup.

  2. make-alien allocates memory for a given type and an optional size (using malloc).

  3. I add nil, a.k.a. () after the allocation so that the REPL does not return the pointer, but that nil value instead. Otherwise, that would no be a real leak because the REPL remembers the last three returned values (See *, **, ***) and we could still have a chance to free the allocated memory.

share|improve this answer

Java (OpenJDK 9), 322 bytes

import sun.misc.*;import java.lang.reflect.*;public class Main{public static void main(String[] args) throws Exception { Constructor<Unsafe> unsafeConstructor = Unsafe.class.getDeclaredConstructor();unsafeConstructor.setAccessible(true);unsafeConstructor.newInstance().allocateMemory(Runtime.getRuntime().maxMemory()/2);}}

Try it online!

This is a other Memory leak that don't use the String Cache. It Allocates half of your RAM and you can't do anything with it.

share|improve this answer
    
You can save a bunch of bytes by obtaining the Unsafe instance from the static variable inside it, like that: import sun.misc.*;class M{static void main(String[]a)throws Exception{java.lang.reflect.Field f=Unsafe.class.getDeclaredField("theUnsafe");f.setAccessible‌​(1<2);((Unsafe)f.get‌​(1)).allocateMemory(‌​1);}} – zeppelin yesterday
    
And you can save some more by replacing the public static void main by a static initializer static{try{}catch(Exception e){}} (which could be a bit more tricky to launch but is nevertheless valid and compilable). – zeppelin yesterday
    
yhea the use of the constructor was used in a Android version of code I used. I will change some things when im @home but I will go the path you went with a single statement ;) – Serverfrog 16 hours ago
    
Remove whitespace, use a instead of args, and remove public. tio.run/nexus/… – Pavel 2 hours ago

Dart, 76 bytes

import'dart:async';main()=>new Stream.periodic(Duration.ZERO).listen((_){});

A bit like the JavaScript answer. When you call .listen on a Dart stream object you are given back a StreamSubscription, which allows you to disconnect from the stream. However, if you throw that away, you can never unsubscribe from the stream, causing a leak. The only way the leak can be fixed is if the Stream itself gets collected, but its still referenced internally by a StreamController+Timer combo.

Unfortunately, Dart is too smart for the other stuff I've tried. ()async=>await new Completer().future doesn't work because using await is the same as doing new Completer().future.then(<continuation>), which allows the closure itself to be destroyed the second Completer isn't referenced (Completer holds a reference to the Future from .future, Future holds a reference to the continuation as a closure).

Also, Isolates (aka threads) are cleaned up by GC, so spawning yourself in a new thread and immediately pausing it (import'dart:isolate';main(_)=>Isolate.spawn(main,0,paused:true);) doesn't work. Even spawning an Isolate with an infinite loop (import'dart:isolate';f(_){while(true){print('x');}}main()=>Isolate.spawn(f,0);) kills the Isolate and exits the program.

Oh well.

share|improve this answer
    
if your main program kept running and doing other stuff, would the garbage collector ever be able to stop the isolate? i ask because my goroutine example sounds similar... i assumed that the fact that the program exits and gives all memory back to the OS doesn't necessarily mean it hasn't leaked. – don bright 5 hours ago

C++, 16 bytes

main(){new int;}

I don't have valgrind to check it leaks, but pretty sure it should. Otherwise I would try:

main(){[]{new int;}();}

Valgrind result

(It does leak indeed)

==708== LEAK SUMMARY:
==708==    definitely lost: 4 bytes in 1 blocks
share|improve this answer
    
What compiler are you using? g++ requires main to have a return type. – Wheat Wizard 18 hours ago
    
@WheatWizard I am using g++ 4.3.2 (not the most recent one) and it compiles just fine. No return type is int by default I think. With -Wall I have a warning though: plop.cpp:1: warning: ISO C++ forbids declaration of 'main' with no type – matovitch 18 hours ago
    
@WheatWizard Sorry, I just saw you gave the c++ example to start the contest. Coming from reddit I only looked at the answers and (strangely) did not saw any C++. I feel a bit dumb. :/ – matovitch 18 hours ago

C 30 bytes

f(){int *i=malloc(sizeof(4));}

Valgrind Results:

         ==26311== HEAP SUMMARY:
         ==26311==     in use at exit: 4 bytes in 1 blocks
         ==26311==   total heap usage: 1 allocs, 0 frees, 4 bytes allocated
         ==26311== 
         ==26311== LEAK SUMMARY:
         ==26311==    definitely lost: 4 bytes in 1 blocks
         ==26311==    indirectly lost: 0 bytes in 0 blocks
         ==26311==      possibly lost: 0 bytes in 0 blocks
         ==26311==    still reachable: 0 bytes in 0 blocks
         ==26311==         suppressed: 0 bytes in 0 blocks
         ==26311== Rerun with --leak-check=full to see details of leaked memory
share|improve this answer
1  
Is it possible to instead just do main(){malloc(1);}? – refi64 15 hours ago
    
@Yea it is! But its already been posted! – Abel Tom 15 hours ago

x86 ASM, 1 byte, assumes a certain kind of stack frame

push AX

Some kinds of stack frames free this at mov SP, BP, some don't. The kinds that don't probably crash but you can avoid that by not returning. For some reason this code golf challenge does not require placing the leak inside a loop as it ought to.

share|improve this answer
    
The language here is machine code, not assembler (it's 7 bytes in assembler), so you might want to give a hexdump of the machine code. However, I don't see how this leaks memory; by definition, this memory is deallocated when the function returns, and corrupting the stack in such a way that the function crashes on return doesn't change that. – ais523 10 hours ago
    
@ais523: They changed the counting rules for assembly so its byte count is as the machine code. – Joshua 6 hours ago

Javascript, 3 bytes

Every string in Javascript is re-created in memory, since they are immutable.

If you allocate a string with something, it will take (at least) 2 bytes (UTF-16).

"1"

Running something like for(var i = 0; i < 1000000; i++)"1";, on Google Chrome, you can see the memory increasing (using the built-in task manager).
It climbs by 10-20kb, using the example code.

share|improve this answer
4  
AFAIK garbage collector will reclaim these orphaned strings, freeing the memory. – zeppelin 2 days ago
    
@zeppelin I haven't seen that effect on Google Chrome. – Ismael Miguel 2 days ago
2  
@IsmaelMiguel I highly suspect that while the memory is not freed immediately Javascript Garbage collector will deallocate them at the end of the process. Your loop does not demonstrate that anything has been leaked only that things are being allocated. – Wheat Wizard 2 days ago
    
@WheatWizard If they are allocated and not de-alloacted, then it's a leak. Right? – Ismael Miguel 2 days ago
1  
@IsmaelMiguel The question is whether or not the memory is de-allocated, by Javascript's garbage collector. I am not an expert in Javascript, so I really don't know how the garbage collector works but your answer does not really convince me that the memory is leaked. Can you run it through any sort of memory debugger? – Wheat Wizard 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.