Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does nested forever leak memory?

This code leaks memory (very fast, be prepared to kill it soon if you try it):

import Control.Monad (forever)

main = do
    forever $ forever $ return ()

(Compiled with -O2, -O, -O0..., ghc 7.0.3) I don't understand why should this leak - I am using quite a lot of such code with exception handler between the forever's and I don't quite understand why is this supposed to leak memory..

I just looked into source for Control.Monad and found this:

{- Note [Make forever INLINABLE]

If you say   x = forever a
you'll get   x = a >> a >> a >> a >> ... etc ...
and that can make a massive space leak (see Trac #5205)

In some monads, where (>>) is expensive, this might be the right
thing, but not in the IO monad.  We want to specialise 'forever' for
the IO monad, so that eta expansion happens and there's no space leak.
To achieve this we must make forever INLINABLE, so that it'll get
specialised at call sites.

Still delicate, though, because it depends on optimisation.  But there
really is a space/time tradeoff here, and only optimisation reveals
the "right" answer.
-}

This bug is supposedly 'fixed'; unfortunately it seems that the nested forever triggers the bug again. Interestingly enough, this definition of forever (borrowed from Control.Monad) triggers the bug:

forever a   = a >> forever a

While the following definition works without problems:

forever a   = a >>= \_ -> forever a

There's something fishy in the >> operator, as I would this code to be equivalent.

like image 366
ondra Avatar asked Dec 25 '11 20:12

ondra


People also ask

What are the causes of memory leaks?

Memory leaks are a common error in programming, especially when using languages that have no built in automatic garbage collection, such as C and C++. Typically, a memory leak occurs because dynamically allocated memory has become unreachable.

Can memory leak happen C#?

If you have implemented a very long-running or infinite running thread that is not doing anything and it holds on to objects, you can cause a memory leak as these objects will never be collected. The fix for this is to be very careful with long-running threads and not hold on to objects not needed.


1 Answers

You were looking at the latest version of base, which is probably not what you are using. The forever in base 4.3.1.0 does not use INLINABLE. If I run your example with GHC 7.2.2 and base 4.4.1.0, I do not get a space leak.

like image 189
Joey Adams Avatar answered Sep 29 '22 20:09

Joey Adams