What do we mean by automatic memory management? How does wxHaskell manage memory?

One advantage of Gtk is its way of dealing with memory. Other libraries, in particular those written in C++, force the user to explicitly allocate and free objects which is not in the spirit of garbage-collected languages like Haskell.

All objects you create in Gtk2Hs are pointed to by ForeignPtrs, that is, when the Haskell variable goes out of scope, the reference count of the underlying object is decreased. If it drops to zero, the Gtk object is discarded. Every time you receive an object from Gtk, e.g. through an event, the binding automatically increases the reference count so that you can safely use the object as long as you want to.

An object can also be destroyed in Gtk, meaning that the memory is still there but you can’t do anything with it anymore other than free the memory. This is a nice feature since even if Gtk destroys an object, using a Haskell reference to it does not crash the program (actions on a destroyed object just don’t do anything anymore).

wxWidget is a library with a C++ spirit, that is memory allocation and initialisation is one thing and destruction and deallocation of memory is one thing. Furthermore, wxWiget object are not reference counted and hence, if the library decides to destroy an object (say, the user closes a window) then the Haskell program has a dangling pointer which, on using it, will usually lead to a crash. Similarly, you need to free all objects you don’t use anymore which can lead to space leaks (in the C sense) in case you forget to do so. It would be very difficult for a binding to impose a proper memory management on top of wxWidgets since a variable that is garbage collected should not destroy the widget it points to, since it could be still in use (e.g. be visible on the screen). Basically you would need to implement a reference-counting scheme around every widget. But even this only solves the problem of freeing memory but does not protect you from using a dangling pointer.

The reason that memory management is important is that not doing it breaks the spirit of Haskell: One of the main advantages of garbage collected languages is that you don’t need to worry about freeing objects. wxHaskell in that sense is worse than any Java Swing/AWT application since even there you don’t have to worry about freeing objects.

Comments are closed.