[Haskell-cafe] memory leak when using "forever"

Tom Ellis tom-lists-haskell-cafe-2013 at jaguarpaw.co.uk
Tue Oct 4 17:19:52 UTC 2016


On Tue, Oct 04, 2016 at 01:51:04PM +0200, Zoran Bosnjak wrote:
> can you please explain why does this simple program leak memory.
>
> But, if I replace loop2 with loop1 (that is: without using "forever"),
> then it does not leak.
>
> import Control.Concurrent
> import Control.Monad
> import Control.Monad.Trans
> import Control.Monad.Trans.Reader
> import Control.Monad.Trans.State
> 
> main :: IO ()
> main = do
>     --let loop1 = (liftIO $ threadDelay 1) >> loop1
>     let loop2 = forever (liftIO $ threadDelay 1)
> 
>     _ <- runStateT (runReaderT loop2 'a') 'b'
>     return ()

My results below.  Looks like there's something wrong with *> for ReaderT
and StateT.  I get a stack overflow even with just

    _ <- runStateT loop ()

and just

    _ <- runReaderT loop ()

8<---

import Control.Concurrent
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State
import Control.Applicative

-- Fine
forever0 a = let a' = a >> a' in a'

-- Stack overflow
forever1 a = let a' = a *> a' in a'

-- Fine
forever2 a = a >> forever2 a

-- Stack overflow
forever3 a = a *> forever3 a

main :: IO ()
main = do
  let loop = forever3 (liftIO $ return ())
  _ <- runStateT (runReaderT loop ()) ()
  return ()                                                                                                                      


More information about the Haskell-Cafe mailing list