text:
Visualize the Euclidean algorithm
The Euclidean algorithm is a widely known algorithm for calculating the greatest common divisor (GCD) of two positive integers.
The algorithm
For the purpose of this challenge, the algorithm is described as below:

Display the two input as adjacent lines of a certain character
e.g. an input of 3,4 can be represented by the adjacent lines 000 and 0000
Turn the first length(short_line) characters in the longer line into another character, say -
now it looks like 000 and ---0
Eliminate the first length(short_line) characters in the longer line.
now 000, 0
Repeat step 2 and 3 until the two have equal length, using the shorter and longer lines after each iteration, e.g.
000,0
-00,0
00,0
-0,0
0,0
You can choose whether to stop here or continue the iteration and turn one of the lines into an empty line.

Each of these steps should be separated by an interval between 0.3s and 1.5s.
The challenge
Write a program that, given two natural numbers as input, creates an output that looks exactly the same as the output of the algorithm above. You can use other non-whitespace printable ASCII characters than 0 and -, but be consistent and use only two characters. You can also use alternative algorithms provided the output, including the timing, is exactly the same as would be produced by the algorithm above.
Examples
This is an example with input 24,35, which are coprimes so their GCD is 1.

This is an example with input 16,42, which have the GCD 2.

Rules

This is a code-golf, so shortest bytes wins
Standard loopholes apply
You can assume input to be positive decimal integers

Unless you are using sed, Retina, ///, etc, in which case you can use unary

Clarifications

The lines that represent the numbers need to stay in their original order, i.e. the first and second lines of the first displayed "frame" need to be the first and second lines respectively, in all subsequent frames.
After the algorithm ends, no additional visible entity should appear. However, this also means that it is okay to blank the lines, if you make sure that the last "frame" is displayed for at least the same amount of time as did all other frames before blanking out.

@WheatWizard great suggestion, on it

Do the lines have to stay in the same relative order? Or can they be reordered between iterations? (Checking because the latter is likely to be much more concise in most languages, and thus I need to know whether I should use that optimization or ignore it due to violating the sepc.)

@ais523 Yes they do :-)

@ais523 Yes it's okay to blank it, but make sure the last frame is given the same display time as the other frames

Can we take the input in unary? (that may save one step of converting from number to sequence of characters)

@LuisMendo Sorry, but no you can't. Thanks for finding another possible loophole :-) The sandbox doesn't really give too much attention to loopholes

@busukxuan It makes sense for that to be banned :-) Can - be replaced by space? Again, that might help, but it would be the same char as possible trailing spaces of the shorter string

@LuisMendo I would actually like space to be legal, but I'm not sure if it's a good idea to allow it for the - replacement only, or if it's more "elegant" to just ban it for both characters.

Not a duplicate, despite the name, but definitely related; both questions are about visualising GCD algorithms, they just picked entirely different algorithms to visualise.

@busukxuan Personally I think I would allow trailing spaces, but perhaps not space as one of the "meaningful" characters

Are you overriding this meta consensus regarding unary input?  I.e is unary input banned for sed answers?

@DigitalTrauma Wow, didn't know that existed! Well, it seems more unfair to ban them than to allow exceptions, so it's ok if you're sed.

Is it mandatory to clear the screen between outputs? Generally I tend to keep this optional in my challenges as I don't really think print '\n'*50 adds much value to the challenge. No criticism intended. Just seeking clarification.

@ElPedro No, only the two lines are relevant

Jelly, 29 bytes
VY“ñc‘ỌœS.⁸
1ẋÇµ+M¦ṚÇt€2Çµ⁻/¿

Try it online!
This defines a function 2Ŀ (not a full program; the TIO link contains a footer that converts a function into a program) that takes a list of two elements as input, and displays the output on the screen (one of our legal I/O methods, and one that is kind-of necessary for this challenge because it talks about the appearance on screen). This assumes that the program is run in a terminal that complies with the ANSI standard (I used gnome-terminal but most will work), and that the terminal is initially empty (which seems like the most sensible default); note that Try it online! does not conform to these assumptions, and thus the output is distorted there (I ran the program locally to verify that it animates as expected). I use 1 where the question uses 0, and 2 in place of -.
Explanation
Helper function 1Ŀ (given a list of two lists of digits, outputs them on the first and second lines of the screen, then waits 0.5 seconds; returns its input)
VY“ñc‘ỌœS.⁸
V                   Convert each list of digits to an integer
 Y                  Separate these integers by newlines
  “ñc‘              {Output that; then restart with} the list [27, 99]
      Ọ             Convert codepoints to characters (i.e. "\x1bc"
       œS.          Wait (œS) 0.5 (.) seconds
          ⁸         {Output that; then return} the initial argument

The string "\x1bc", when sent to an ANSI-compatible terminal, is interpreted as a control code to reset the terminal; this clears the screen and moves the cursor to the top left corner (thus resetting the terminal ready for the next output).
The helper function is named 1Ŀ (Jelly autogenerates names of this form for functions, and in fact there's no other way to name them), but it can be referred to simply as Ç from the main program (because the language has shorthand for functions with numbers nearby).
Main function 2Ŀ (implements the task requested in the question)
1ẋÇµ+M¦ṚÇt€2Çµ⁻/¿
1ẋ                  Convert input to unary
  Ç                 Call helper function (producing one animation frame)
   µ         µ  ¿   While
              ⁻/      the elements differ:
     M¦               Change the largest element
    +  Ṛ                by adding corresponding elements of the other element
        Ç             Call helper function (producing one animation frame)
         t€2          Delete all 2s from each side of each element
            Ç         Call helper function (producing one animation frame)

JavaScript (ES6), 128 124 bytes

t=0
f=
(a,b,o,c,d)=>setInterval(e=>{e=[b,d,a,c];o.data=`-0
-0`.replace(/./g,c=>c.repeat(e.pop()));c|d?c=d=0:a>b?a-=c=b:b-=d=a},1e3)
<form><input id=a><input id=b><button onclick=clearTimeout(t),t=f(+a.value,+b.value,o.firstChild)>Go!</button><pre id=o>

Python 2, 152 146 bytes
import time
s,o='-0'
a,b=input()
while a*b:
 d,e=o*a,o*b
 if a>b:a=a-b;d=s*b+o*a
 elif b>a:b=b-a;e=s*a+o*b
 else:a=0
 print d+'\n'+e;time.sleep(1)

Try it online!

Takes two comma-separated integers as input

That's a nice answer.

Javascript (ES6), 215 194 ... 135 129 127 bytes
a=>b=>F=(c=0)=>alert('-'[d='repeat'](e=c&a>b&&b)+'0'[d](a-=e)+`
`+'-'[d](f=c&a<b&&a)+'0'[d](b-=f))|a-b|c&&setTimeout(F,1e3,1-c)

Usage
This takes input in a variation on currying. To use it, fist assign the function to a variable (for example G), then call it like this:
G(5)(6)()

Explanation
Somewhat recursive function that calls itself after 1 second as long as the algorithm hasn't finished. It keeps track of a third variable c that determines whether a and b should be changed (if c is 1, it's time for change).
First, the function writes something to the console. If c is 0, it writes two strings of zeroes with a newline inbetween. Since c is initialised to 0, we can take advantage of this, and set up global variables f and g that hold some strings we need often (like 0 and repeat).
Otherwise, it builds up a string with zeroes and minuses. All such strings consist of two parts: first some (call this amount A) minuses, then some (call this amount B) zeroes, then a newline, then some (call this amount D) minuses and lastly some (call this amount E) zeroes.
If the first input is smaller than the second input, we need to remove zeroes from the second input, so A is zero, B equals the first input, D equals the first input and E equals the second input minus the first input. If the first input is not smaller than the second input, the reverse applies (A is the second input, B is the first input minus the second input etc.).
With these new values for the input and a switched variable c, the function is scheduled to be called again in 1e3 milliseconds, which equals one second.
Notes

Uses alert for output
Uses 0 and -, just like in the examples
Delay between steps is 1000 ms (1 second)
After the first step, the function will (due to the nature of JavaScript) return some number which is to be ignored
The version on TIO outputs everything at once, pasting the code in the browser console will properly take the delays into account

Try it online
Try it here!

Python 2, 208 204 194 bytes
-4 with thanks to @math_junkie for the sneaky trick with time.sleep
-10 with thanks to @busukxuan for clarifying the "clear screen" rule.
def z(a,b,y='-',w=1):
 import time;c,d,n,s='0'*a,'0'*b,'\n',time.sleep
 if w:print c+n+d;s(1)
 if b>a:d=y*a+d[a:]
 else:c=y*b+c[b:]
 print c+n+d;s(1)
 if c!=d:z(len(c),len(d),('','-')[y!='-'],0)

Try it online!
Pretty sure this could be more golfed. It pains me to duplicate the print and the for loop to create the pause but I can't find a way round it at the moment.
Notes

The pause now uses a hint from @math_junkie
Doesn't fully work on TIO as it stores the output and dumps it out when the program finishes. Works fine in the console though.

You should be able to save some bytes using import time, s=time.sleep and s(1) instead of a loop for the delay

Thanks @math_junkie - I tried most combinations using time.sleep but missed that one. Will give it a go.

@math_junkie - comes to 215 for me. Maybe I am missing something stupid. Can you post an example on Try it Online?

Try it here

perl, 161 149 bytes
...without indentations and newlines:
($a,$b)=map 0 x$_,@ARGV;
sub p{say"\n$a\n$b";sleep 1}p;
while($a ne$b){
  ($A,$B)=$b lt$a?(\$a,\$b):(\$b,\$a);
  map$$A=~s/0/-/,1..length$$B;
  p;
  $$A=~s/-//g;
  p
}

Put it into a file gcd.pl and run like this:
perl -M5.010 gcd.pl 16 42

The -M5.010 flag to perl is free, so you can save a few bytes by using say over print…\n. Additionally, I'm pretty sure it's terser to give your anonymous subroutine a name, rather than storing it in a variable.

Thx to ais523 for tips to shave off 12 bytes

GNU Sed (with exec extension), 88
Score includes +3 for -zrf options to sed.
p
:
x
esleep 1
g
ta
:a
s/o+//p
t
s/^((O+)(O+)\n\2\b|(O+)\n\4\B)/\L\2\U\3\4\n\2\L\4\U/p
t

Input is given as two newline separated unary integers, using the upper case O as digits.
For example, the 16, 42 example may be run as:
printf "%0*d\n%0*d\n" 16 0 42 0 | tr 0 O | sed -znrf euclidvis.sed

As per the latest comments, I am not clearing the screen between iterations.

V, 47 44 bytes
Àé0á
Àé0Hqwmmjlhmmkl@wqòHî@w
gs`mlhv0r-gsÓ-ò

Try it online!
The header and footer on TIO just modify gs to copy the current two lines to the bottom of the screen, and then delete the first two at the end.  This visualizes the operation for TIO, but if you ran it in V (without the header and footer), it would just wait a second between each operation.
Àé0                     " Print (Arg1) zeroes
   á                    " Newline
Àé0                     " Print (Arg2) zeroes
   H                    " Go home
    qwmmjlhmmkl@wq      " Store a recursive macro in w that finds the shorter line
                  ò     " recursively
                   Hî@w " find the longest line
gs                      " wait a second
  `mlhv0r-              " replace the zeroes of the long line with -
          gs            " wait a second
            Ó-          " delete all -
              ò         " end recursion

Do you really need the ending ò?

It hangs without it, unsure why.  Going to wait until I have a computer with V on it to debug any


text:
Predecessor-completed Ascii Cubes
The first Predecessor-completed Ascii Cube (PAC 1) is a simple cube with side length 1 and looks like this:
 /////\
/////  \
\\\\\  /
 \\\\\/

The PAC 2 is a geometric shape such that combining it with its predecessor (the  PAC 1) completes a side length 2 cube:
      front                back
   /////////\           /////////\
  /////////  \         /////////  \
 /////\\\\\   \       /////////    \
/////  \\\\\   \     /////////      \
\\\\\  /////   /     \\\\\\\\\      /
 \\\\\/////   /       \\\\\\\\\    /
  \\\\\\\\\  /         \\\\\\\\\  /
   \\\\\\\\\/           \\\\\\\\\/

Because the back-view is kind of boring, we are only interested in the front-view.
The same goes for the PAC 3: With some visual thinking the PAC 2 can be turned around and plugged into the PAC 3 to form a solid side length 3 cube:
     /////////////\
    /////////////  \
   /////\\\\\\\\\   \
  /////  \\\\\\\\\   \
 /////   /////\\\\\   \
/////   /////  \\\\\   \
\\\\\   \\\\\  /////   /
 \\\\\   \\\\\/////   /
  \\\\\  /////////   /
   \\\\\/////////   /
    \\\\\\\\\\\\\  /
     \\\\\\\\\\\\\/

And so on with PAC 4:
       /////////////////\
      /////////////////  \
     /////\\\\\\\\\\\\\   \
    /////  \\\\\\\\\\\\\   \
   /////   /////////\\\\\   \
  /////   /////////  \\\\\   \
 /////   /////\\\\\   \\\\\   \
/////   /////  \\\\\   \\\\\   \
\\\\\   \\\\\  /////   /////   /
 \\\\\   \\\\\/////   /////   /
  \\\\\   \\\\\\\\\  /////   /
   \\\\\   \\\\\\\\\/////   /
    \\\\\  /////////////   /
     \\\\\/////////////   /
      \\\\\\\\\\\\\\\\\  /
       \\\\\\\\\\\\\\\\\/

Task:
Write a full program or function which takes a positive integer n as input and returns or prints the corresponding front-view of PAC n exactly as shown above. Additional trailing white space is acceptable.
This is code-golf, so try to use as few bytes as possible in the language of your choice.

Is it okay to print laterally inverted output, i.e. switch left and right?

No, it's part of the challenge to keep the "lighting" consistent.

Usually the bounty for code-golf questions goes to the shortest answer to encourage competition and the golfing of answers, but it really can't be enforced, and you're more than welcome to award it to any answer that deserves it.

JavaScript (ES6), 229 bytes

f=
(n,l=n*4+1,r=1,i=n*2,g=a=>` / \\ /
`.replace(/./g,c=>c.repeat(a.pop())))=>n?g([r,,l,--i])+g([r,2,l,--i])+f(n-1,l-1?1:r-4,r-1?1:l-4).replace(/(\S).*(.)/g,r-1?`$1   $&$2$2$2$2`:`$1$1$1$1$&   $2`)+g([r,2,l,,,i])+g([r,,l,,,i+1]):``
<input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o>

Batch, 559 432 400 bytes
@echo off
set m=
for /l %%i in (1,1,%1)do call set m=  %%m%%
call:c "%m:~2%" %m: =//%/\
exit/b
:c
setlocal
set m=%~1%2%~3
echo  %m%
echo %m:/\=/  \%
set s=%~1
if "%s:~,1%"=="/" goto g
set t=%2
set t=%t:~3,-3%
if %t:~,1%==/ (call:c "%s:~2%////" /\%t:/=\% "   \%~3")else call:c "%s:~2%/   " %t:\=/%/\ "\\\\%~3"
:g
set m=%m:/=-%
set m=%m:\=/%
set m=%m:-=\%
echo %m:\/=\  /%
echo  %m%

Explanation: The bottom half of the cube is drawn by reflecting the top half. The halves are further split into seven six three strips parts, as per this diagram showing the top half:
1       12/////////////////\233
1      12/////////////////  \233
1     ////12/\\\\\\\\\\\\\23   \3
1    ////12/  \\\\\\\\\\\\\23   \3
1   /////   12/////////\23\\\\   \3
1  /////   12/////////  \23\\\\   \3
1 /////   ////12/\\\\\23   \\\\\   \3
1/////   ////12/  \\\\\23   \\\\\   \3

The indentation (which decreases every row) and the left triangle, which increases every other row
The middle shrinking zigzag triangle, with the small triangle on alternate sides every other row
The right triangle, which increases in sync with the left

Edit: Saved over 20% by improving the code that reflected the top to the bottom half. Saved almost 10% by merging the left two and middle three strips.

Canvas, 36 bytes
；Ｘø；｛１ｘ／╋
ø╶｛«５⁸２²４×⁸²«１╋²«＼＋；↔５３╋｝═

Try it here!

The ASCII art version of SOGL was outgolfed by SOGL in an ASCII art challenge?

@dylnan Canvas didn't have the diagonal space prepend built-in which could golf this a bit. Didn't feel right adding a built-in for the challenge

got it. Just curious. Still two cool languages

SOGL V0.12, 32 bytes
ø.∫4*I└*2∙f«5└*∙+¼F«╝┼;↔±53╬5}╬±

Try it here!
Simple explanation:
1. iterate for each of 1..x
2. make a ⌐ shape with the width of i*4+1 and height = (0-indexed)i // 2
3. pad it so it looks like ⦧
4. append a "\" shape to that horizontally
5. insert the previous step inside that reversed
6. after everything, mirror vertically
full program:
ø                                 push an empty string - starting stage
 .∫                          }    iterate over 1..input
   4*                               multiply the 1-indexed counter by 4
     I                              and add 1
      └*                            repeat "/" that many times
        2∙                          and repeat vertically twice. Top 2 lines are done
          f«                        push the 0-indexed counter floor divided by 2
            5└*                     push "/" repeated 5 times
               ∙                    and repeat that vertically by the result of the "f«"
                +                   add vertically, creating a "⌐" shape
                 ¼                  prepend each next line with one less space than the above
                  F«                push 1-indexed counter floor divided by 2
                    ╝               create a "\" diagonal that long
                     ┼              and append it horizontally. Shell is done of this hexagon
                      ;↔±           get the previous item on the stack and reverse it horizontally
                         53╬5       and at [5;3] insert the previous result in this
                              ╬±  once everything's done, mirror vertically to finish the hexagon

Ruby,  174 167 169  167 bytes
->n{a=(1..m=n*4).map{' '*m}
(-n..0).map{|i|(-2*i).times{|k|a[y=k+2*j=n+i][m+~k+i*2,2+k*2-s=4*i]=?/*(1-~j%2*s)+'  '*k+?\\*(1-j%2*s)
a[~y]=a[y].tr('/\\','\\\\/')}}
a*$/}

Try it online!
creates an array of n*4 strings filled with spaces, then overwrites it with successively smaller cubes.
Commented code
->n{a=(1..m=n*4).map{' '*m}                 #make an array of n*4 strings of n*4 spaces (up to centreline of final output)
  (-n..0).map{|i|                           #iterate through cube sizes from n down to 0 (i is negative -n to 0)
    (-2*i).times{|k|                        #iterate through the number of lines in the top half of the cube
      a[y=k+2*j=n+i][m+~k+i*2,2+k*2-s=4*i]= #overwrite the correct part of the correct line
      ?/*(1-~j%2*s)+'  '*k+?\\*(1-j%2*s)    #with the correct string of the form "/spaces\" with an additional -4*i symbols on one side
      a[~y]=a[y].tr('/\\','\\\\/')          #copy the current line from top half into bottom half, subsituting / for \ and vice versa
    }
  }
a*$/}                                       #return the elements of the array a, concatenated with newlines $/

Haskell, 232 227 224 187 183 180 175 bytes
m '/'='\\'
m '\\'='/'
m c=c
r=reverse
k=map
n?s=('/'<$[1..4*n])++s
f 0=[]
f n=n?"/\\":n?"/  \\":[1?k m(r s)++"   \\"|s<-f$n-1]
s="":k(' ':)s
((++).r<*>k(k m)).zipWith(++)s.r.f

The anonymous function in the last line takes an integer argument and yields the lines to be printed for a cube of that size.
The idea is to use recursion to draw larger cubes from smaller ones. Lets look at the upper half of a cube of size 1. Then we get the upper half of a cube of size 2 by mirroring the former half and add a fixed pattern of slashes and spaces around it:

                                         /////////\
                                        /////////  \
     /////\    ==>    /\\\\\    ==>    /////\\\\\   \
    /////  \         /  \\\\\         /////  \\\\\   \

So the algorithm to draw a cube of size n is

Get the lines for the upper cube half of size n-1.
Mirror each line (by flipping /s and \s), and pad //// and    \ around.
Prepend two lines with the pattern ////n plus /\ and /  \.
Mirror the resulting lines to get the full cube.
Pad lines with appropriate number of spaces.

Anonymous functions are allowed, so you can drop g=. (\l->r l++k(k m)l) is the same as liftM2 (++) r (k(k m)), which again can be shortened to (++).r<*>k(k m). Try it online!

Python 2, 254 234 226 203 201 199 bytes
Finally sub 200!
P=[];n=0
M=lambda r:(u''+r).translate({47:92,92:47})
exec r"n+=1;q='/'*4;P=[q*n+'/\\',q*n+'/  \\']+[q+'%s   \\'%M(r[::-1])for r in P];"*input()
print'\n'.join(l.center(8*n)for l in(P+map(M,P[::-1])))

Tricks:
This function is used to swap all \ with / and vice versa
A bit long in Python2 - works only with unicode
Check out this for how it works
M=lambda r:(u''+r).translate({47:92,92:47})

Generates new top two rows for each iteration
For now I can't find compact way to receive this lines from previous iteration
P=[q*n+'/\\',q*n+'/  \\']

Reverse all rows of previous iteration and swap slashes
[q+'%s   \\'%M(r[::-1])for r in P]

Copy top half, reversed by rows, swap slashes
P+map(M,P[::-1])

Neat method for center padding strings
l.center(8*n)

Try it online!

Stax, 36 bytes
äª.$u>↓Z╙╝B↨EXª¡╜?Xáhç∙╩p/♂ù⌠r↨c⌐f/*

Run and debug it
This approach builds up the top half of the output iteratively.  It executes the main block the specified number of times.  In that block, each row is mirrored and has a prefix and suffix added.  The top two new rows are added separately.  When all the rows are built, they're centered, and then the bottom is mirrored vertically.
Here's the program unpacked, ungolfed, and commented.
{               begin block to repeat
  iHYH^H'\*     make a string of '\' characters and set the Y register
                  pseudo-code: push(((y = (i * 2)) * 2 + 1) * 2 * '\')
                  given the 0-based iteration index `i`, let y = 2 * i
                  and push a string consisting of (i*8 + 2) backslashes
  2M            split the string into to equal size (i*4 + 1) substrings
  ~+            push array to input stack and concatenate
                  on the first iteration, this is a no-op
                  subsequently, it prepends the array to the result so far
  {             begin a block to use for mapping
    4'\*+       append 4 backslashes to this element
    :R          "brace-wise" reverse
                  this reverses the string AND the slashes in it
    |YH3+92&    write 92 to index (++y * 2 + 3) in the array
                  this puts the trailing backslash at the correct position
                  this will be an out of bounds index, so the string will grow
                  92 is the character code for backslash
  m             execute map using block
}*              repeat block specified number of times
|C              vertically center all rows
{               begin block for output mapping
  Q             output this line without popping
  :Rr           "brace-wise" reverse, and then actually reverse
                  net effect is to swap forward and backward slashes
m               execute map using block
rm              reverse array, and output all rows

Run this one

Haskell, 193 bytes
Longer than the winner, but the approach may be interesting -- uses even cos and pi :)
Code:
i s e f|max e f>s=""|max e f<s=" "|e==s="\\"|1<2="/"
w n y x=head$do{d<-[1..n];o<-[-2*d..2*d];z<-[(cos(pi*(n-d)))*o+x];i(2*d)(abs$z-y)(abs$z+y-1)}++" "
n!h=h<$>[1-2*n..2*n]
f n=((2*n)!)<$>n!w n

Run it like this:
mapM_ putStrLn (f 4)

This program basically 'draws' many diamonds like this one:
------------------------
------------------------
-----------/\-----------
----------/  \----------
---------/    \---------
--------/      \--------
--------\      /--------
---------\    /---------
----------\  /----------
-----------\/-----------
------------------------
------------------------

Function i s e f 'draws' one diamond of size s, where e, f are (abs$z-y)(abs$z+y-1).
Function w moves the diamonds drawn by i
to correct places. head used in its definition is responsible for looking at the topmost layer only.
Try it here

Maybe someone has some ideas how to make the code shorter?

Charcoal, 42 bytes
ＦＮ«↗×⊗⊕ι/↓↘Ｇ↖²→⊕×⁴⊕ι↘²\Ｇ←⁴↘⊕⊗ι→⁴\Ｍ⁴→‖Ｔ»‖Ｍ↓

Try it online! Link is to verbose version of code. Explanation:
ＦＮ«

Draw the cubes from the smallest to the largest. (Drawing from the largest to the smallest meant that I ended up with a mirror image for odd numbers which cost too many bytes to fix.)
↗×⊗⊕ι/

Print a line of /s. (This will become the \s on the right, but the drawing is done mirrored because it's golfier to mirror at the end of the loop.)
↓↘Ｇ↖²→⊕×⁴⊕ι↘²\

Print the top two rows of \s. (Drawing all the \s in one polygon meant that the cursor ended up in an awkward position which cost too many bytes to fix.)
Ｇ←⁴↘⊕⊗ι→⁴\

Print the left four rows of \s. (The fifth row comes from the previous cube.)
Ｍ⁴→

Move to the start of the next cube.
‖Ｔ»

Reflect horizontally ready for the next cube.
‖Ｍ↓

Mirror everything vertically to complete the cube.

source: Stack Exchange

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

sort: votes


text:
Leak Memory in as few bytes as possible
Your task is to write code that will leak at least one byte of memory in as few bytes as possible.  The memory must be leaked not just allocated.
Leaked memory is memory that the program allocates but loses 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.

Perhaps you could have different ranges of amount leaked and depending on how much you leak you lose x% of your byte count

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

Related. Not a duplicate, though, because most answers to that question form an infinite reachable structure in memory rather than actually leaking memory.

what is the idea? That the mem cannot be freed? I guess this would require native execution for garbage collected languages or exploiting bugs.

I have read only the title of your question and I immediately went to a C++ online compiler to put new int inside the main function! After I've read the question's body, and because the answer is there I will not post that as an answer!

I see how languages designed for golfing fail miserably on this one ...

DOS batch file, 3 bytes. win :-)

Leaks depend from OS, i would Know if program end, all the memory it is released to the Os, even the one of leaks. The question has one reason if it is requested one function that leak memory...

I think this is how I justify 16 gigs of RAM for a casual desktop

I think it would have been better if the questione asked for a program that didn't leak and then removing characters to make a program that did.  That way it would be the program leaking and not all those interpreters and compilers that leak on every program they run.

@JerryJeremiah Ideally if I were to ask this again I would require two programs one of which leaks more memory that the other and your score would be the length of the one that leaks more.  That way if every program leaks memory you can still participate, you just have to find a way to leak additional memory on top of the default.  (Or plug the existing leak).

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)

Is there any way to get the valgrind output on TIO? The empty program itself isn't very enlightening :P

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

I tried installing valgrind earlier, but it requires some permissions the sandbox context doesn't have.

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

This also works in Node JS.

This feels like a new standard loophole in the making...

Finally a Perl script that I can understand.

If Perl one-liners are good, no-liners are better !

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

Why is linux not freeing memory when process exits and nothing else is using the memory? I'm sure this scenario is not possible on windows, if there are no handles to shared memory it will get freed, and all the handles are released when process shuts down

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

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

Thank you for posting this. I just protected TIO against shared memory leaks.

@Dennis That's why I didn't post a TIO link. I didn't know if it was protected or not.

I like how you use the word problem to describe the scenario where the program leaks less memory than intended.

@AndrewSavinykh there are Linux APIs, that were considered OK at the time, but became obsolete with creation of better alternatives and saner development practices. Unlike in Windows, there is no central entity to forcibly declare stuff deprecated, everyone is free to keep using it, even if better alternatives exist. File locks are supplanted by file leases, but some people don't even know those exist; shared memory got replaced by tmpfs, but many still use it by inertia. On the bright side, there is no Vista-like breakage-feasts :)

Would f(k){shmget(k,1,512);} work?

@Dennis That depends on how strict we are about loosing access. k will often be set to the first argument of the function called before f(). That means that there is a good chance we can figure out what k originally was.

But int k has the same problem, assuming it is one. https://tio.run/nexus/c-gcc#@5@moalQzcWZmVeikG3NxVlQBGSlaSippsTkKekoZGtac9VycaVr5AFVARm5iZl5EA3pGoZGxkBZTqABQDX//wMA Btw, shmget(k,1); seems to work just fine.

@Dennis If the function modifies it's first argument then k will also change to that. I think that is good enough to loose the key. Thanks!

@Dennis For shmget(k,1);, that doesn't always work for me. Without the third argument of 512 (which is IPC_CREAT) it doesn't always create the new segment.

Right, I should have tested it more than once. main(k){shmget(&k,1,512);} should work instead of the rand() approach.

@Dennis After the shmget call we still know what &k is so we still have the key.

But that's a full program. How would we recover &k?

@Dennis The question says: "memory that the program allocates but looses the ability to access before it can deallocate ...". The program still has the key so it could deallocate. I'll add it, but keep the rand() one because this is borderline.

@AndrewSavinykh you can almost get the same thing with GlobalAddAtom in Windows. Also CreateFileMapping.
But GlobalAddAtom isn't unrecoverable, and neither is CreateFileMapping so I guess they don't really count.

Why does the main method not count towards the bytes?

@ThomasWeller In the verification? Because my submission is just the function. int main(){f();} is there to call f(). In other words, an example of usage.

clock() would be much shorter than srand();rand()

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)

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)

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

Yep, most of us know the feeling ;) @RayKoopa

+1 for Ti Basic. I spent most of my 9th grade year programming those things.

Do you need Pause  at the end?  You could save 2 bytes.

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

A simpler "leak" under these rules would be to create a program named prgmA consisting of the single command prgmA (2 bytes). This creates the same kind of "leak" (technically blowing an internal stack). Neither one is leaking "memory" in the OP's sense, and neither one is "unrecoverable" in OP's sense either (since the While "leak" can be reclaimed by hitting an End, and the infinite recursion can be stopped by... making it not-infinite) — but I don't think the OP's definitions make a whole lot of sense in non-C languages anyway. :)

Nice idea @Quuxplusone, but do notice that in this example there is no recursion and no overflow like there would be with your example.

@Timtech: It's just a question of semantics (as admittedly so was the OP's question). I'd say that in both cases the control flow is looping forever and the internal data structures of the Basic interpreter (in one case the "active programs" stack, in the other case the "active End-able constructs" stack) are growing without bound, so to me there's no difference. In neither case is any "heap memory" allocated; TI-Basic doesn't have that concept. (But see my next comment.)

I'd say the closest thing to a "heap memory allocation" in TI-Basic is 1→L₁(1+len(L₁, and the closest thing to a "leak" is 1→ʟA. If the program does this and then exits, it's up to the calculator user to go delete that newly created list.

Python <3.6.5, 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, eventually reported as part of CPython issue 31787 and fixed in Python 3.6.5 and Python 3.7.0. (Also, yes, property([]) is a thing you can do.)

Has a bug report been sent?

@mbomb007: CPython issue 31787.

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 its 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 its 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 circumstances. Well except for the power switch maybe.
Test
Here is a test suite:
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.

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

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.

Wouldn't the challenge be complete by just using class L{~L(){new L();}}? AFAIK the for(;;) only makes it leak memory faster, right?

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

Not really. Eventually one finalized will be ignored. The corresponding object will be eaten regardless.

Thanks that is very interesting situation with garbage collection in c#!

How does this work if L is never instantiated in the first place?

It doesn't. It also doesn't work if you don't start the process. Sarcasm aside: the challenge asked for some code that can be executed that leaks. In this case instantiating L is the equivalent of running a process or calling a function.

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

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.

Haha I love that you've typed 'Golfed', makes me curious about the ungolfed version

it might look like this if(window && window.setInterval && typeof window.setInterval === 'function') { window.setInterval(0); }

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

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

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.

@user2428118
Brute-forcing the timer ID, might indeed work, in some implementations.
But in general the order and range of ID values is not guaranteed,
as well if they will be reused or not (most implementations specify the ID to be an opaque numeric token).
So, I don't think there is a "legitimate" way to cancel timers w/o knowing the ID.
Anyway, finding a "leak", which can not be "hacked" or "brute-forced" is (IMHO) not the point of this challenge, e.g. most malloc-based answers can be "fixed" with the malloc hooks, pretty easily, but that
does not disqualify them.

@user2428118 As zeppelin says, this is no more "legitmate" than saying the C/C++ leaks aren't "real" because you could brute force calls to free()

Wow, not many challenges where JavaScript is an actual contender...

@zeppelin user2428118 only disputed your claim that it's impossible to cancel, without saying anything about whether it should count as a leak. Yes, it's possible to cancel the interval. Yes, it's a leak and a valid answer nonetheless. Just change the "making it impossible to cancel" to something like "making it impossible to cancel without guessing the id" to correct that one small inaccuracy.

Would a pair of backticks (template string) instead of (0) or even setInterval() work, too?

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)

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)

awesome. posts like this led me to explore Rust over the past year, definitely one of the most fun languages i have tried to learn.

I am not aware of any operating systems that have a usize defined as u8. It should be fn malloc(_:usize);.

@Sapphire_Brick using the correct function prototype would waste 3 bytes. thus the comment "This assumes the wrong ABI is acceptable".

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.

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

Surly it's just a case of adding two strings together, as in my prior comment, or does intern not work like that? It's perfectly possible, I would say. This answer also is neither a program, nor a self-contained piece of code that leaks memory, as I don't believe it will compile by itself (it has to have some type-asserting context)

Yep, if happen to know the string content in advance, which is an "external" piece of information. I.e. consider this is a library function and you do not see the source.

it has to have some type-asserting context

I don't think there is a good consensus on Java lambdas currently, and there are well-accepted Java-lambda answers around, which do not provide any explicit type information.
But anyway, in this specific case it is not just a lambda, but an object method reference, against the string literal (which only possible type is a concrete final class java.lang.String), pointing to the 0-arg trim() method of it, making it pretty unambiguous.

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

Forgive me for saying, I think this is ridiculous. You could just as well say that every cache is a memory leak. The java GC won't clear this memory since it is intentionally reserved for performance reasons - to allow == comparisons (which, anyway, is not entirely true, since interned Strings are weakly-referenced).

You could just as well say that every cache is a memory leak
Exactly, if a) What you put into it does not expire by itself b) There is no way to explicitly remove anything from it, or enumerate it's content c) You have lost the key. Now you have a piece of memory allocated for something you can not access or remove any longer, hence it is a leak.

And I don't think interned string literals are subject to garbage collection, even in implementations which do GC on the interned strings pool per-se.

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

One thing I don't really know how it has to been handled: you can't use this exactly code and run it through javac. So are java answers always (like C# or other languages with that buildup) with all that class and "public static void main" part.

@Serverfrog, I don't think there is a good consensus about it, really. There are well-accepted lambda-based answers (like this one), which do not include all this repeated boilerplate code. Moreover,  the method reference, as used in this answer, points to a concrete method of a final class (i.e. it implies more type information than a generic lambda). But I guess that would make a good topic to discuss on Meta.

@zeppelin You used a specific String, not a random one. So we have access to the code and we can show you that that code isn't unreachable. It isn't a leak. Your best bet if you want to use the string cache is to generate a random String with an unspecified seed and .intern() it. so we can't go back to access the String again. Using any specific String will make it accessible again.

@zeppelin: A memory leak is not when it's unlikely or difficult to reach an object. We can access this string simply by guessing correctly. That's not a leak. (If guessing is somehow a magical superability that doesn't count, we can open and read the .class file, even within the program, and there's probably some way to use reflection to determine the string's contents too.)

@Serverfrog functions are permitted, including lambdas. It is a good idea to include code to invoke the function or explain which functional interface can wrap the lambda, which this answer did. For golfing purposes, however, only the lambda is included in the byte count - not any other "glue" code to include it in a larger program.

@user2357112 On a machine with a finite memory, you can access a value stored in any piece of memory simply by guessing it correctly, but that does not mean that such a thing as memory leaks do not exist. there's probably some way to use reflection to determine the string's contents too could you demonstrate this ? (hint, String.intern() is implemented in the native code).

Won't Java garbage collect the original string, thus not making this a memory leak?

@tenmiles - it is a string literal, so it should not be garbage collected.

Personally I like this answer. However I think the best argument against it is that the GC does clean up interned Strings in newer versions (7+) of java. Interned Strings used to be allocated in PermGen but were moved to the heap as of Java 7. Furthermore I think we need better clarification about what a "memory leak" is. The argument I'm seeing is that we can still get a reference to the leaked String. I don't think this matters because we would still have a failure to release that memory even though it's reachable. Failure to release vs lost reference.

@Poke - that is true for the dynamically allocated strings in Java 7+ (at least for the HotSpot family of VMs), but a string literal, as used in this answer, won't be garbage collected (as well as it's entry in the intern pool).

Supplier<String> f = ". "::trim; f.get(); var x = ". "; Now ". " is reclaimed. So this is not a leak.

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!

The normal implementation of malloc will result in memory being freed on process exit.

@Joshua Yeah, but that's implementation defined behaviour.

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

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.

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'

golf check: this is 2 bytes shorter than calling C.malloc(8), since you need to import"C"

There are three kinds of answers. The low-level languages where you just malloc then discard it, the garbage collected languages where you create an infinite loop that doesn't give the garbage collector time to deallocate memory, and the garbage collected languages that leak memory due to a bug in the interpreter.

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.
It's a bug in Java until 1.3 included as it was fixed afterwards.
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());
        }
    }
}

Since this works only on specific Java versions, you should say "Java 3" in your header instead.

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.

This was my idea too. Damn.

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.

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 The last line could be wrapped in a function to fix that

@NobodyNada, if I were to put the last line in a do block that would fix the problem zeppelin raised right?

@Dopapp Yeah; a do would work as well.  Good idea!

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}

@SebastianOsiński, oh yes I didn't think of that!

@Dopapp It's nice to see a Swift answer :) I submitted one, myself: http://codegolf.stackexchange.com/a/111013/11490

This isn't a memory leak, because it's still accessible. You would have to set it to nil

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:

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.

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.

@JonHanna quite right. My IDisposable paranoia seems to have got the better of me.

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

<!-- language: lang-c# --> Thanks for this & nice answer! (It's C# so I love it)

@Metoniem I think you may have commented on the wrong answer ;) You can suggest the language clause as an edit to MrPlauch's C# answer.

@VisualMelon to be fair my answer stretches the bounds of this challenge. Since it is not a classic memory leak. It is more like turning the entity responsible for avoiding leaks into ... exploding. As a result it "leaks". Your answer however is the "real" memory leak, as implemented in C#

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:

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.

Common Lisp (SBCL only), 28 26 bytes
sb-alien::(make-alien int)

You run it like so: sbcl --eval 'sb-alien::(make-alien int)'; nothing is printed nor returned, but the memory allocation happens. If I wrap the form inside a (print ...), the pointer is displayed in the REPL.

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.
make-alien allocates memory for a given type and an optional size (using malloc).
When executing this in the REPL, add 0 after the allocation so that the REPL does not return the pointer, but that 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.

2 bytes removed thanks to PrzemysławP, thanks!

Can't you use 1 (or 2, 3, etc.) instead of () so that you return value 1? It would save 1 byte. Also is this answer REPL only? Maybe if you load code with load you can not include () or anything at the end, because it will not be accessible anyway?

@PrzemysławP You are right on both points, I tried with eval and this works as you said. Thanks a lot!

Java (OpenJDK 9), 322 220 bytes
import sun.misc.*;class Main{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);}}

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.
Thanks to zeppelin for saving all the bytes

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

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

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

Remove whitespace, use a instead of args, and remove public. https://tio.run/nexus/java-openjdk9#bY2xTgMxDIZfJWPCECTWAyQEDAwsICbEYFzfYZQ4le1ri6o@@3GFGyrB5N//91meuK6berBRcmXDfNYtzSdsIBeQISv1hdCPSJy0B6Qw7M3BGcOm8SpUYInPrizD6xsk/9C2tXC/Q1o7N9nfNjHXEb3p5YsY9HQ9/owTcPULMhYwywP5Hc1RaXXixNT9uctGfoNIZvxeKM4t/WcJbR/mDQQppgylNASnR6pNv@LTKM6Vjl@XODsVdgtO5xepOxym6Rs

true can be replaced with 1>0

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

@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

@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. :/

Consensus is that you can count just []{new int;} as a C++ function (the challenge didn't specify a whole program).

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

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.

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

Is it possible to instead just do main(){malloc(1);}?

@Yea it is! But its already been posted!

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.

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.

Swift, 12 bytes
[3,5][0...0]

Explanation:
This is a de-facto memory leak that can occur in any language, regardless if the language uses memory manual management, automated reference counting (ARC, like Swift), or even sweeping garbage collection.
[3,5] is just an array literal. This array allocates enough memory for at least these those 2 elements. The 3 and 5 are just arbitrary.
Subscripting (indexing) an Array<T> produces an ArraySlice<T>. An ArraySlice<T> is a view into the memory of the Array it was created from.
[3,5][0...0] produces an ArraySlice<Int>, whose value is [3]. Note that the 3 in this slice is the same 3 element as the 3 in the original Array shown above, not a copy.
The resulting slice can then be stored into a variable and used. The original array is no longer referenced, so you would think it could be deallocated. However, it cannot.
Since the slice exposes a view onto the memory of the array it came from, the original array must be kept alive as long as the slice lives. So of the original 2 element-sizes worth of memory that were allocated, only first element-size worth of memory is being used, with the other the one being required to exist so as to not allocate the first. The second element-size of memory is de-factor leaked.
The solution to this problem is to not keep alive small slices of large arrays for long. If you need to persist the slice contents, then promote it to an Array, which will trigger the memory to be copied, thus removing the dependancy on the original array's memory:
Array([3,5][0...0])

Whaaaaaaaaaaat?

@Sapphire_Brick Hmm?

@AlexanderReinstateMonica I'm just shocked that such a simple code causes a memory leak.

@Sapphire_Brick Yep, I haven't seen any automated memory management systems that can clear up something like this. The book keeping required to know that you're only using a small portion of a large allocated object is probably not worth the performance cost it introduces

Solution 1: C (Mac OS X x86_64), 109 bytes
The source for golf_sol1.c
main[]={142510920,2336753547,3505849471,284148040,2370322315,2314740852,1351437506,1208291319,914962059,195};

The above program needs to be compiled with execution access on the __DATA segment.
clang golf_sol1.c -o golf_sol1 -Xlinker -segprot -Xlinker __DATA -Xlinker rwx -Xlinker rwx

Then to execute the program run the following:
./golf_sol1 $(ruby -e 'puts "\xf5\xff\xff\xfe\xff\xff\x44\x82\x57\x7d\xff\x7f"')

Results:
Unfortunately Valgrind does not watch for memory allocated from system calls, so I can't show a nice detected leak.
However we can look at vmmap to see the large chunk of allocated memory (MALLOC metadata).
                                VIRTUAL   REGION
REGION TYPE                        SIZE    COUNT (non-coalesced)
===========                     =======  =======
Kernel Alloc Once                    4K        2
MALLOC guard page                   16K        4
MALLOC metadata                   16.2M        7
MALLOC_SMALL                      8192K        2         see MALLOC ZONE table below
MALLOC_TINY                       1024K        2         see MALLOC ZONE table below
STACK GUARD                       56.0M        2
Stack                             8192K        3
VM_ALLOCATE (reserved)             520K        3         reserved VM address space (unallocated)
__DATA                             684K       42
__LINKEDIT                        70.8M        4
__TEXT                            5960K       44
shared memory                        8K        3
===========                     =======  =======
TOTAL                            167.0M      106
TOTAL, minus reserved VM space   166.5M      106

Explanation
So I think I need to describe what's actually going on here, before moving onto the improved solution.
This main function is abusing C's missing type declaration (so it defaults to int without us needing to waste characters writing it), as well how symbols work. The linker only cares about whether of not it can find a symbol called main to call to. So here we're making main an array of int's which we're initializing with our shellcode that will be executed. Because of this, main will not be added to the __TEXT segment but rather the __DATA segment, reason we need to compile the program with an executable __DATA segment.
The shellcode found in main is the following:
movq 8(%rsi), %rdi
movl (%rdi), %eax
movq 4(%rdi), %rdi
notl %eax
shrq $16, %rdi
movl (%rdi), %edi
leaq -0x8(%rsp), %rsi
movl %eax, %edx
leaq -9(%rax), %r10
syscall
movq (%rsi), %rsi
movl %esi, (%rsi)
ret

What this is doing is calling the syscall function to allocate a page of memory (the syscall mach_vm_allocate uses internally). RAX should equal 0x100000a (tells the syscall which function we want), while RDI holds the target for the allocation (in our case we want this to be mach_task_self()), RSI should hold the address to write the pointer to the newly created memory (so we are just pointing it to a section on the stack), RDX holds the size of the allocation (we're just passing in RAX or 0x100000a just to save on bytes), R10 holds the flags (we're indicating it can be allocated anywhere).
Now it's not plainly obvious where RAX and RDI are getting their values from. We know RAX needs to be 0x100000a, and RDI needs to be the value mach_task_self() returns. Luckily mach_task_self() is actually a macro for a variable (mach_task_self_), which is at the same memory address every time (should change on reboot however). In my particular instance mach_task_self_ happens to be located at 0x00007fff7d578244. So to cut down on instructions, we'll instead be passing in this data from argv. This is why we run the program with this expression $(ruby -e 'puts "\xf5\xff\xff\xfe\xff\xff\x44\x82\x57\x7d\xff\x7f"') for the first argument. The string is the two values combined, where the RAX value (0x100000a) is only 32 bits and has had a one's complement applied to it (so there's no null bytes; we just NOT the value to get the original), the next value is the RDI (0x00007fff7d578244) which has been shifted to the left with 2 extra junk bytes added to the end (again to exclude the null bytes, we just shift it back to the right to get it back to the original).
After the syscall we're writing to our newly allocated memory. The reason for this is because memory allocated using mach_vm_allocate (or this syscall) are actually VM pages, and are not automatically paged into memory. Rather they are reserved until data is written to them, and then those pages are mapped into memory. Wasn't sure if it would meet the requirements if it was only reserved.
For the next solution we'll be taking advantage of the fact that our shellcode has no null bytes, and so can move it outside of our program's code to reduce the size.
Solution 2: C (Mac OS X x86_64), 44 bytes
The source for golf_sol2.c
main[]={141986632,10937,1032669184,2,42227};

The above program needs to be compiled with execution access on the __DATA segment.
clang golf_sol2.c -o golf_sol2 -Xlinker -segprot -Xlinker __DATA -Xlinker rwx -Xlinker rwx

Then to execute the program run the following:
./golf_sol2 $(ruby -e 'puts "\xb8\xf5\xff\xff\xfe\xf7\xd0\x48\xbf\xff\xff\x44\x82\x57\x7d\xff\x7f\x48\xc1\xef\x10\x8b\x3f\x48\x8d\x74\x24\xf8\x89\xc2\x4c\x8d\x50\xf7\x0f\x05\x48\x8b\x36\x89\x36\xc3"')

The result should be the same as before, as we're making an allocation of the same size.
Explanation
Follows much the same concept as solution 1, with the exception that we've moved the chunk of our leaking code outside of the program.
The shellcode found in main is now the following:
movq 8(%rsi), %rsi
movl $42, %ecx
leaq 2(%rip), %rdi
rep movsb (%rsi), (%rdi)

This basically copies the shellcode we pass in argv to be after this code (so after it has copied it, it will run the inserted shellcode). What works to our favour is that the __DATA segment will be at least a page size, so even if our code isn't that big we can still "safely" write more. The downside is the ideal solution here, wouldn't even need the copy, instead it would just call and execute the shellcode in argv directly. But unfortunately, this memory does not have execution rights. We could change the rights of this memory, however it would require more code than simply copying it. An alternative strategy would be to change the rights from an external program (but more on that later).
The shellcode we pass to argv is the following:
movl $0xfefffff5, %eax
notl %eax
movq $0x7fff7d578244ffff, %rdi
shrq $16, %rdi
movl (%rdi), %edi
leaq -0x8(%rsp), %rsi
movl %eax, %edx
leaq -9(%rax), %r10
syscall
movq (%rsi), %rsi
movl %esi, (%rsi)
ret

This is much the same as our previous code, only difference being we're including the values for EAX and RDI directly.
Possible Solution 1: C (Mac OS X x86_64), 11 bytes
The idea of modifying the program externally, gives us the possible solution of moving the leaker to an external program. Where our actual program (submission) is just a dummy program, and the leaker program will allocate some memory in our target program. Now I wasn't certain if this would fall within the rules for this challenge, but sharing it nonetheless.
So if we were to use mach_vm_allocate in an external program with the target set to our challenge program, that could mean our challenge program would only need to be something along the lines of:
main=65259;

Where that shellcode is simply a short jump to itself (infinite jump/loop), so the program stays open and we can reference it from an external program.
Possible Solution 2: C (Mac OS X x86_64), 8 bytes
Funnily enough when I was looking at valgrind output, I saw that at least according to valgrind, dyld leaks memory. So effectively every program is leaking some memory. With this being the case, we could actually just make a program that does nothing (simply exits), and that will actually be leaking memory.
Source:
main(){}

==55263== LEAK SUMMARY:
==55263==    definitely lost: 696 bytes in 17 blocks
==55263==    indirectly lost: 17,722 bytes in 128 blocks
==55263==      possibly lost: 0 bytes in 0 blocks
==55263==    still reachable: 0 bytes in 0 blocks
==55263==         suppressed: 16,316 bytes in 272 blocks

Plain English, 71 70 58 35 bytes
Removed 1 byte by deleting a blank line.  Removed 12 bytes by eliminating the "bogon" type definition, and using the parent "thing" type instead of the "bogon" subtype.  Removed 23 bytes by switching from a complete program, to just a routine that leaks memory.
Golfed version:
To x:
Allocate memory for a thing.

Ungolfed version that is a complete program, uses a subtype definition, and does not leak memory:
A bogon is a thing.

To do something:
  Allocate memory for a bogon.
  Destroy the bogon.

To run:
  Start up.
  Do something.
  Shut down.

If the golfed version of "x" is called, it will leak memory in proportion to the number of times "x" is called.  In the golfed version, "Deallocate the thing." would fix the memory leak.
Plain English checks for memory leaks by default.  When the version that leaks memory is run, a dialog box will appear just before the program shuts down.  The dialog box has a title of "debug", a message of "1 drip", and an "OK" button.  The more times the leaking function is called, the larger the number of "drips" in the message. When the version that does not leak memory is run, the dialog box does not appear.
In Plain English, a "thing" is a pointer to an item in a doubly-linked list.  "Thing", "to start up", and "to shut down" are defined in a module called "the noodle", which needs to be copied in (usually as a separate file) into each project.  "A", "the", "to", "to allocate memory", and "to destroy" are defined in the compiler.

c, 9 bytes
main(){}

Proof:
localhost/home/elronnd-10061: cat t.c
main(){}
localhost/home/elronnd-10062: valgrind gcc t.c
==10092== Memcheck, a memory error detector
==10092== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==10092== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==10092== Command: gcc t.c
==10092==
t.c:1:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
 main(){}
 ^~~~
==10092==
==10092== HEAP SUMMARY:
==10092==     in use at exit: 178,518 bytes in 73 blocks
==10092==   total heap usage: 362 allocs, 289 frees, 230,415 bytes allocated
==10092==
==10092== LEAK SUMMARY:
==10092==    definitely lost: 4,659 bytes in 8 blocks
==10092==    indirectly lost: 82 bytes in 5 blocks
==10092==      possibly lost: 0 bytes in 0 blocks
==10092==    still reachable: 173,777 bytes in 60 blocks
==10092==         suppressed: 0 bytes in 0 blocks
==10092== Rerun with --leak-check=full to see details of leaked memory
==10092==
==10092== For counts of detected and suppressed errors, rerun with: -v
==10092== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

You're not actually leaking memory; gcc is. This should also work with the empty program. Try gcc src.c && valgrind ./a.out, which should produce a clean result.

@user77406 The perl answer which is 0 bytes and the unlambda answer which is 1 byte also have this property.  Like all things in code golf, if it isn't prohibited in the standard loopholes, anything is game if you get the right answer.

Haskell, 29 bytes
Yet another "malloc and forget" answer:
import Foreign
main=()<$new 0

This time it is in Haskell, which is normally a garbage collected language, but the Foreign Function Interface gives access to raw malloc operations.
Explanation
The function new allocates a new block of memory, stores a copy of the argument at that location and returns a pointer to it. In this case, we store the value 0 :: Double. Then, we ignore the pointer by using (<$) :: a -> IO (Ptr Double) -> IO a to replace the return value with the unit (()).

Swift, 42 38 bytes
class a{var b: a};var b:a?=a();b!.b=b;b=nil

Explanation
Swift uses automatic reference counting (ARC) for garbage collection. It works by keeping a count of the number of references to an object, and deallocates it right before the reference count diminishes to zero.
Take a look at the following pseudocode:
let x be an address of allocated memory
allocate 16 bytes, then store the address of those 16 bytes in x

One of the worst things to do is...
set x to NULL

Because now we no longer know where those 16 bytes are located.
ARC prevents (most) objects from being made inaccessible. However, what ARC doesn't help with is cycles, or reference loops.
For example, \$a\$ has a reference to \$b\$, and \$b\$ has a reference to \$a\$. The problem is that they rely on each other to keep a non-zero reference count.
Recall that the above code looks like
class a{var b: a!};do{var b:a?=a();b!.b=b;b=nil}

The first part...
class a {
   var b: a!
}

...lays the foundation for a reference cycle.
var b: a? = a();

Sets b to to a new a, and b allowed to be nil. Right now, the reference count is 1.
b!.b = b

Assert that b is not nil (because it's allowed to be, as it will be later), set property b of b to b.
This creates a cycle; b has a reference to b. Right now, the reference count is 2, but only one of those references come from an accessible source, namely b.
b = nil

Whoops. The reference count is 1, because b has a reference to b, but now, nothing else has a reference to b, creating a memory leak.

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.

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: They changed the counting rules for assembly so its byte count is as the machine code.

ZX Spectrum BASIC, 2 bytes
GO SUB PI

Explanation: both GO SUB and PI are single tokens taking one byte. GO SUB will actually jump to line nr. 3, but the number 3 would take 5 bytes whereas PI takes only one.
ZX Spectrum BASIC has no memory management, so the return address on the stack remains until you re-initialize BASIC with NEW or CLEAR or RUN a program or until you use the RETURN command. If used as a part of a stored BASIC program, the memory would remain leaked even after the program terminates (and if you repeat the GO SUB PI enough times, the machine will run out of memory).

PHP, 32 bytes
gc_disable();$x[]=&$x;unset($x);

Run like this:
php -r 'gc_disable();$x[]=&$x;unset($x);'

Explanation
This causes a circular reference, which can only be caught (and freed) by the circular reference collector (which I disabled). Test to see memory leak effects:
# Without disabling circular ref collector.
php -nr 'for(;$a++<100000;){$x[]=&$x;unset($x);}echo memory_get_usage()."\n";'
> 353944
# Circular ref collector disabled.
php -nr 'gc_disable();for(;$a++<100000;){$x[]=&$x;unset($x);}echo memory_get_usage()."\n";'
> 40354096

Julia, 60 56 bytes
addprocs();!a=while 1>0 s=convert(SharedArray,a)end;![9]

This entry is based on the bug https://github.com/JuliaLang/julia/issues/20424 , and is very likely to be invalidated by a future update.
It can be done with less code, but the loop nails it down that it's an actual leak, caused by a bug, and not just the GC waiting its merry time before it starts collecting garbage. Also, GC will probably be alerted and start cleaning everything up if you start putting any significant amount of other garbage onto the heap, so I want to get the OOM error up before anyone starts cluttering the heap with other garbage.
Explained (as far as I can tell):
#Spawn some child processes
addprocs();

#Iterative subroutine that does nothing but generate and then immediately forget shared arrays en masse
!a=while 1>0 s=convert(SharedArray,a)end;

#Let it rip
#For whatever reason, GC never gets around to cleaning the shared arrays up
#The OutOfMemoryError should pop up soon enough
![9]

Batch, 2 bytes
a^

This is based on my favorite StackOverflow post of all time. (Wayback link since the original is removed.) I'll copy the explanation directly from there:

The Bug Explained
The bug is that when a caret is detected, the next character is read
  from the file (to be 'escaped'). If the caret is the last character of
  the file, this results in a logic error, as when a call to
  get_next_char is made, the file pointer is incremented by one; in this
  case that puts it passed the EOF. Since the EOF is effectively ignored
  when the command parser continues to read the next input, it
  essentially 'resets' its file pointer due to the EOF+1 error. In this
  case, putting the file pointer to EOF+1 causes the pointer to be at
  some large negative number, and since file's can't go below 0, it's
  file pointer is basically reset to 0 and the parsing continues from
  the beginning of the file.

It should be noted that, based on my own testing, the issue seems to be resolved in Windows 10.

Bash (4.4.20), 0 bytes

Verification
$ valgrind bash main.sh
==1172== Memcheck, a memory error detector
==1172== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1172== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==1172== Command: bash main.sh
==1172==
==1172==
==1172== HEAP SUMMARY:
==1172==     in use at exit: 33,849 bytes in 379 blocks
==1172==   total heap usage: 514 allocs, 135 frees, 54,210 bytes allocated
==1172==
==1172== LEAK SUMMARY:
==1172==    definitely lost: 12 bytes in 1 blocks
==1172==    indirectly lost: 0 bytes in 0 blocks
==1172==      possibly lost: 0 bytes in 0 blocks
==1172==    still reachable: 33,837 bytes in 378 blocks
==1172==         suppressed: 0 bytes in 0 blocks
==1172== Rerun with --leak-check=full to see details of leaked memory
==1172==
==1172== For counts of detected and suppressed errors, rerun with: -v
==1172== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

SmileBASIC, 8 bytes
?POP(@L)

Due to a bug, using POP on a string literal will use up memory, which can't be freed without restarting the system.

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.

AFAIK garbage collector will reclaim these orphaned strings, freeing the memory.

@zeppelin I haven't seen that effect on Google Chrome.

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

@WheatWizard If they are allocated and not de-alloacted, then it's a leak. Right?

@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?

Hmm, I don't think you can really fit 1000000 "1" strings in 10-20kb of memory. And if that is a per-iteration increase, then it is too much for a single string object.

At least in Node, "1" doesn't seem to leak any memory, even with 1,000,000 iterations. The empty program still leaks 672 bytes though, so I guess this is still valid.

Is there any way to test this on Windows? The builtin task manager shows an increased memory usage everytime I run this.

The question says that the memory must be leaked, not just allocated.

@mbomb007 What counts as a leak?

@IsmaelMiguel in the case of JavaScript, allocations unreachable by the GC, for a (non-golfing) example: document.body.addEventListener("click", ()=>{}) since the event listener handle is not retained, it can't be removed programmatically, and since its attached to a DOM node the GC can't remove it. Its the same thing as the setTimeout answer.

C/C++, GCC; 46 bytes
int main(){while(1){int* x=new int;}return 0;}

What does it do?
int main()
{
    // Start an infinite loop:
    while (1)
    {
        // Create a variable `x` and point to a new integer:
      int* x = new int;
    }

    return 0;
}

The code above uses an infinite loop to point to a new address that is not deleted.

No, No, No! new isn't a C operator, and your code could be made much shorter anyways. For C++, a shorter code would be int main(){new int;}, for C, a shorter code would be void*malloc(size_t);main(){malloc(9);}

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

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


text:
Imaginary Parts of Non-Trivial Riemann Zeroes
Introduction
According to the Riemann Hypothesis, all zeroes of the Riemann zeta function are either negative even integers (called trivial zeroes) or complex numbers of the form 1/2 ± i*t for some real t value (called non-trivial zeroes). For this challenge, we will be considering only the non-trivial zeroes whose imaginary part is positive, and we will be assuming the Riemann Hypothesis is true. These non-trivial zeroes can be ordered by the magnitude of their imaginary parts. The first few are approximately 0.5 + 14.1347251i, 0.5 + 21.0220396i, 0.5 + 25.0108576i, 0.5 + 30.4248761i, 0.5 + 32.9350616i.
The Challenge
Given an integer N, output the imaginary part of the Nth non-trivial zero of the Riemann zeta function, rounded to the nearest integer (rounded half-up, so 13.5 would round to 14).
Rules

The input and output will be within the representable range of integers for your language.
As previously stated, for the purposes of this challenge, the Riemann Hypothesis is assumed to be true.
You may choose whether the input is zero-indexed or one-indexed.

Test Cases
The following test cases are one-indexed.
1       14
2       21
3       25
4       30
5       33
6       38
7       41
8       43
9       48
10      50
50      143
100     237

OEIS Entry
This is OEIS sequence A002410.

Mathematica, 23 bytes
⌊Im@ZetaZero@#+.5⌋&

Unfortunately, Round rounds .5 to the nearest even number, so we have to implement rounding by adding .5 and flooring.

PARI/GP, 25 bytes
There's not much support in GP for analytic number theory (it's mostly algebraic), but just enough for this challenge.
n->lfunzeros(1,15*n)[n]\/1

Sage, 34 bytes
lambda n:round(lcalc.zeros(n)[-1])

Try it online
This solution is a golfed form of the program found on the OEIS page.
lcalc.zeros is a function (which is thankfully spelled the shorter way, rather than zeroes for an extra byte) that returns the imaginary parts of the first n non-trivial Riemann zeta zeros. Taking the -1st index returns the nth zero (1-indexed), and round rounds it to the nearest integer. In Python 3, round uses banker's rounding (half-to-nearest-even), but thankfully Sage runs on Python 2, where round uses half-up rounding.