[C2hs] Storable (Maybe a) leaks memory?

Bjorn Bringert bringert at cs.chalmers.se
Sun Jun 10 18:53:56 EDT 2007

In the C2HS.hs which is generated by 'c2hs -l', I found this code:

instance Storable a => Storable (Maybe a) where
   sizeOf    _ = sizeOf    (undefined :: Ptr ())
   alignment _ = alignment (undefined :: Ptr ())

   peek p = do
              ptr <- peek (castPtr p)
              if ptr == nullPtr
                then return Nothing
                else liftM Just $ peek ptr

   poke p v = do
                ptr <- case v of
                         Nothing -> return nullPtr
                         Just v' -> new v'
                poke (castPtr p) ptr

In the poke implementation, 'Foreign.Marshal.Utils.new' is used.  
'new' uses malloc, and would thus most likely lead to memory leaks,  
since the user of this instance probably doesn't know that he needs  
to free the block pointed to by the written value. Or did I miss  
something clever here?

The best alternative I can see is to restrict it to Storable a =>  
Storable (Maybe (Ptr a)), and skip the call to 'new', but that  
requires extensions.


More information about the C2hs mailing list