0

I'm working on a Haskell project with a graphical user interface written with gtk2hs. When I quit my program, 90% of the time I get a segfault. (I noticed that quite recently, because I usually kill my program with a Ctrl-C on the terminal when developing which doesn't cause a segfault.)

Anyway, I've tracked the source of the segfault with gdb and it's always due to a call to gtk_range_get_value (). Having some scales I guessed what happened was that some part of my program queried the value of a scale when the scale had already been destroyed, hence the segfault.

My intuition was confirmed after making the following code which creates a scale and after destroying the main window demands the value it carries:

import Graphics.UI.Gtk

main :: IO ()
main = do
  initGUI
  window <- windowNew
  set window [containerBorderWidth := 10, windowDefaultWidth := 250]
  adj <- adjustmentNew 1 0 100 1 1 0
  scale <- vScaleNew adj
  containerAdd window scale
  widgetShowAll window
  onDestroy window mainQuit
  mainGUI
  rangeGetValue scale >>= print

However there is something I found strange, when I try and do the same with a spin button, the code doesn't segfaults and gives me a value:

import Graphics.UI.Gtk

main :: IO ()
main = do
  initGUI
  window <- windowNew
  set window [containerBorderWidth := 10, windowDefaultWidth := 250]
  adj <- adjustmentNew 1 0 100 1 1 0
  spin <- spinButtonNew adj 1 0
  containerAdd window spin
  widgetShowAll window
  onDestroy window mainQuit
  mainGUI
  spinButtonGetValue spin >>= print

So here is my question: is it normal that I get a segfault with rangeGetValue and not with spinButtonGetValue? If it is, is there a way to prevent a segfault when demanding a value of something that doesn't exist anymore?

Guerric Chupin
  • 461
  • 2
  • 13
  • 1
    I am not an expert of gtk2hs, but perhaps you should not use its functions after `mainGUI` returned? – chi Aug 03 '16 at 16:09
  • Yes that seems logical, but then the question are why can I get the value of a `spinButton` reliably, and is there a way to prevent a call to this function inside a callback for instance after `mainGUI` as returned? – Guerric Chupin Aug 03 '16 at 17:07
  • 1
    This might be a "feature" coming from the C side of GTK: just because we free'd an object and we access the free'd memory this does not mean that we realiably get a segfault. It might work just fine, e.g. because noone reused that free memory so far... One might expect a better memory safety from Haskell (via garbage collection), but the gtk2hs can not guarantee much after `mainGUI` returns. Keep in mind that I am speculating here -- again, I am not familiar with gtk2hs. – chi Aug 03 '16 at 17:36

0 Answers0