newCString -- to 'free' or not?

Sven Panne Sven.Panne at
Sun Sep 26 06:43:38 EDT 2004

Glynn Clements wrote:
> Peter Simons wrote:
>>When I create a CString with Foreign.C.String.newCString, do
>>I have to 'free' it after I don't need it anymore? Or is
>>there some RTS magic taking place?
>>How about and all those other
>>newXYZ functions? 
> Yes. The new* functions allocate the memory with malloc, and you have
> to free it yourself. OTOH, the with* functions allocate the memory
> with alloca, and it is freed automatically. [...]

Just to be nitpicking: The FFI does *not* guarantee that Haskell's
malloc(Bytes)/realloc(Bytes)/free is the same as C's malloc/realloc/free.
So you should not e.g. use C's free for something allocated via Haskell's

Apart from that, it may help to remember the following "equations":

    alloca = malloc + free (exception-safe!)
    new = malloc + poke
    with = alloca + poke

Depending on your needs, pooled allocation may an option, too:

In that case, all allocations are belong to a given pool and memory is
deallocated when the pool in question is. Furthermore:

    withPool = newPool + freePool (exception-safe!)


More information about the Glasgow-haskell-users mailing list