[Haskell-cafe] peekCString & free memory
Duncan Coutts
duncan.coutts at googlemail.com
Sun Nov 29 13:02:48 EST 2009
On Sun, 2009-11-29 at 18:00 +0100, El Barto wrote:
> Hello,
> I get a segfault when I do
> str <- peekCString ptr
> free ptr
> return (Just str)
As Thomas says, you've not really given us enough info here.
I'll make some guesses and observations anyway :-)
> But not when I don't free the C pointer.
Are you sure the C code does not also free the memory? That would lead
to a double-free which can easily manifest as a segfault.
> I also get the same behaviour with ByteString.packCString...
That's pretty odd since packCString does not free the C string, it makes
a copy. I suppose it could possibly segfault if your C string was not
actually null terminated (as C strings must be).
There are also variants that do not copy, such as
unsafePackMallocCString. See the docs for a description.
> Could you please tell me if the memory is correctly freed by GHC when
> I don't do it myself?
> And how can I specify a custom free function (i.e. xmlFree function in
> libxml2)?
See the documentation for ForeignPtr.
> Maybe I should use a data type with two fields : the String/ByteString
> and the ForeignPtr to the CString?
Is your C String supposed to be freed using the C free() function, or is
it supposed to be freed using xmlFree() or something?
Duncan
More information about the Haskell-Cafe
mailing list