Fix for memory leaks (GHC #7936 and #4218)

https://ghc.haskell.org/trac/ghc/ticket/4218
https://ghc.haskell.org/trac/ghc/ticket/7936