FFI Ptr question

Alastair Reid alastair@reid-hoffmann.net
Thu, 3 Jul 2003 11:26:07 +0100

paul@theV.net wrote:
> > The wierd thing is, I cannot use the the function
> > Foreign.Marshal.Alloc.free to free the ptr. I must
> > use my own C function to do a simple free() call.

Derek Elkins wrote:
> You didn't allocate it with the Foreign library, why would you expect to
> free it with it?  Actually, I'm kind of surprised it doesn't work,
> nevertheless I don't believe that the intent of the Alloc module is to
> free memory allocated by a foreign language, or allocate memory that
> will be freed by a foreign language.  [...]

Foreign.Marshal.Alloc almost certainly uses either the allocator that is 
native to the language used to implement the Haskell runtime system.  This is 
usually C so using the C 'free' function will often work but if your Haskell 
code were translated to Java instead, it would probably be allocated by a 
Java library and should be freed by the same Java library.  

Or Foreign.Marshal.Alloc might be optimized by exploiting the Haskell garbage 
collector in some way and so the memory has to be released in a way that 
informs the Haskell GC.

In general (not just in Haskell's FFI), any time you allocate memory from a 
given memory pool or library, you should free it into the same memory pool/ 
library.  (We tend not to be aware of this rule because most programs have 
just one allocator.)

We could have avoided this problem by defining Foreign.Marshal.Alloc as a 
frontend for malloc/free.  We didn't do so mostly because 
Foreign.Marshal.Alloc is intended to be language independent (i.e., your code 
should still work if interfacing to Java or if your Haskell code is compiled 
to/ interpreted by a Java program) and, in small part, because malloc/free 
implementations are so damn inefficient.

Alastair Reid