* Haskell Cafe on a space leak caused by the garbage collector that [http://www.haskell.org/pipermail/haskell-cafe/2010-June/079444.html did not recognize a selector-like function call]

* Haskell Cafe on a space leak caused by the garbage collector that [http://www.haskell.org/pipermail/haskell-cafe/2010-June/079444.html did not recognize a selector-like function call]

* Haskell libraries on [http://www.haskell.org/pipermail/libraries/2010-September/014420.html Make lines stricter to fix a space leak]

* Haskell libraries on [http://www.haskell.org/pipermail/libraries/2010-September/014420.html Make lines stricter to fix a space leak]

[[Category:Glossary]]

[[Category:Glossary]]

Revision as of 22:43, 4 June 2011

A memory leak means that a program allocates more memory than necessary for its execution.
Although Haskell implementations use garbage collectors, programmers must still keep memory management in mind.
A garbage collector can reliably prevent dangling pointers,
but it is easily possible to produce memory leaks, especially in connection with lazy evaluation.
Note that a leak will not only consume more and more memory but it will also slow down the garbage collector considerably!
Maybe it is even the reason for the widely spread opinion
that garbage collectors are slow or not suited for realtime applications.

1.2 Building up unevaluated expressions

The problem is, that the runtime system does not know, whether the intermediate sums are actually needed at a later point,
and thus it leaves them unevaluated.

I.e. it stores something equivalent to

1+2+3+4

instead of just

10

.

You may be lucky that the strictness analyzer already removes the laziness at compile time,
but in general you cannot rely on it.
The safe way is to use seq to force evaluation of intermediate sums.

This is done by

foldl'

.

foldl' (+) 0 [1..1000000::Integer]

2 Detection of memory leaks

A memory leak can be detected by writing a test that should require only a limitted amount of memory
and then run the compiled program with restricted heap size.
E.g. you can restrict the heap size to 4 MB like in this example:

$ ./mytest +RTS -M4m -RTS

3 A note on GHCi

If you are noticing a space leak while running your code within GHCi, please note that interpreted code behaves differently from compiled code: even when using `seq`.