[Haskell-cafe] IORef memory leak

Don Stewart dons at galois.com
Fri Jun 19 12:47:24 EDT 2009


dvde:
> Don Stewart schrieb:
>> dvde:
>>   
>>> Don Stewart schrieb:
>>>     
>>>> It is not possible to write a modifyIORef that *doesn't* leak memory!
>>>>         
>>> Why? Or can one read about it somewhere?
>>>     
>>
>>
>> Try writing a version of this program, using modifyIORef only, such 
>> that it doesn't exhaust the heap:
>>
>>     import Data.IORef
>>     import Control.Monad
>>     import System.IO.Unsafe
>>
>>     ref :: IORef Int
>>     ref = unsafePerformIO $ newIORef 0
>>     {-# NOINLINE ref #-}
>>
>>     main = do
>>         modifyIORef ref (\a -> a + 1)
>>         main
>>
>> Run it in a constrained environment, so you don't thrash:
>>
>>     $ ./A +RTS -M100M
>>     Heap exhausted;
>>     Current maximum heap size is 99999744 bytes (95 MB);
>>     use `+RTS -M<size>' to increase it.
>>
>> The goal is to run in constant space.
>>
>> -- Don
>>
>>   
> Hm, do you say it is not possible to write a modifyIORef function that  
> does not leak memory, or do you say it is not possible to use the  
> (existing) modifyIORef without having memory leaks?


The latter. atomicModifyIORef is harder though still, since it is a
primop with the same properties as modifyIORef :/

> So would it make sense to create a strict modifyIORef' function?


Very much so. In fact, I'd argue the vast majority of uses are for the
WHNF-strict version.

-- Don


More information about the Haskell-Cafe mailing list