I have a C function that creates a null terminated string and returns a pointer to it, there is also corresponding deallocation function.
foreign import ccall unsafe "get_str" getStr :: IO CString
foreign import ccall unsafe "free_str" freeStr :: CString -> IO ()
I want to create a Haskell String from the returned CString, and free CString as soon as possible.
do cStr <- getStr
str <- peekCString cStr
freeStr cStr
-- here str is used
Is it safe to free cStr before str is used? In other words, does peekCString create Haskell String all at once, or is it created lazily?
peekCString is strict — it doesn’t suspend the loop via unsafeInterleaveIO, for example, so once you have the head of the string, you’ve definitely already computed the tail. Here’s the implementation: