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.
You were looking at the latest version of
base, which is probably not what you are using. Theforeverin base 4.3.1.0 does not useINLINABLE. If I run your example with GHC 7.2.2 and base 4.4.1.0, I do not get a space leak.