tracing segfaults with FFI

Simon Marlow simonmar at
Wed Jan 4 07:36:35 EST 2006

Gaal Yahas wrote:
> I have these two functions:
>     freezeNode node = do
>         ptr     <- newStablePtr node
>         new (castPtr $ castStablePtrToPtr ptr)
>     thawNode nodePtr = do
>         deRefStablePtr (castPtrToStablePtr nodePtr)

You're attempting to deref the StablePtr, and also run it as an IO 
action!  I bet the original value wasn't an IO action, right?

You probably want something like

      thawNode nodePtr = do
         node <- deRefStablePtr (castPtrToStablePtr nodePtr)
         -- and do something with node here

in general, try to keep as much type information as possible.  That is, 
avoid the use of castPtrToStablePtr and its inverse, by giving correct 
types to your FFI functions (you haven't shown more of the code so I 
don't know if this applies in your case).

> What am I doing wrong? More generally, how do I approach this kind of
> problem? What tools exist that can help me debug FFI code?

Tools are a bit thin on the ground.  gdb can help you debug crashes that 
happen in C code, for for Haskell code your best tool is still 
putStr/printf/trace.  Gurus can use gdb on Haskell code, and I'm happy 
to help out (there should probably be a wiki page on how to do this, 
actually), but it's definitely not for the faint hearted.


More information about the Glasgow-haskell-users mailing list