[Haskell-cafe] FFI Query: How to free a CString allocated in Haskell

Peter Gammie peteg42 at gmail.com
Mon Apr 28 23:46:09 EDT 2008


On 28/04/2008, at 7:23 PM, Bulat Ziganshin wrote:

> Hello Verma,
>
> Monday, April 28, 2008, 4:11:51 PM, you wrote:
>
>>      newCString str
>
>> Now once I call this function from C code, I am freeing the allocated
>> memory using free function. I want to confirm that this is the right
>> thing to do.
>
> yes, i've traced this function down to mallocArray -> mallocBytes ->
> malloc() calls

Depending on how you feel about it, Bulat's response either entirely  
answers your question or is neither here nor there.

If you want to write portable code, you should check with the FFI  
spec. If you just want to write code that works with GHC as it  
presently is, you can strace it or whatever.

As Bulat has already given you the pragmatic answer, allow me to grind  
my axe a little. In the FFI spec on p33, we find:

> newCString :: String -> IO CString
> newCStringLen :: String -> IO CStringLen
>
> Allocate a memory area for a Haskell string and marshal the string  
> into its C representation.
> There are two variants of the routine, one for each supported string  
> representation. The
> memory area allocated by these routines may be deallocated using  
> MarshalAlloc.free.

OK, so back on p19 we find:

> free :: Ptr a -> IO ()
>
> Free a block of memory that was allocated with malloc, mallocBytes,  
> realloc, reallocBytes,
> or any of the allocation functions from MarshalArray (see Section  
> 5.9).

and we can draw the inference (reading between the lines) that this  
function need not have a relation to C's malloc. (Roughly, the  
intention is to allow a Haskell implementation to use whatever memory  
management it likes.)

So no, using C's free is not the right thing to do. It will probably  
work in the real world, but you should try to use Haskell's free if  
possible.

cheers
peter


More information about the Haskell-Cafe mailing list