4.22. MarshalAlloc

The module MarshalAlloc provides operations to allocate and deallocate blocks of raw memory (i.e., unstructured chunks of memory outside of the area maintained by the Haskell storage manager). These memory blocks are commonly used to pass compound data structures to foreign functions or to provide space in which compound result values are obtained from foreign functions. For example, Haskell lists are typically passed as C arrays to C functions; the storage space for such an array can be allocated by functions (such as mallocBytes) contained in the present module.

malloc       :: Storable a =>        IO (Ptr a)
mallocBytes  ::               Int -> IO (Ptr a)

alloca       :: Storable a =>        (Ptr a -> IO b) -> IO b
allocaBytes  ::               Int -> (Ptr a -> IO b) -> IO b

reallocBytes :: Ptr a -> Int -> IO (Ptr a)

free         :: Ptr a -> IO ()

The functions mallocBytes, reallocBytes, and free correspond to the standard C functions malloc(), realloc(), and free(), respectively. The function malloc essentially behaves like mallocBytes, but allocates a block of memory whose size is determined by Storable.sizeOf. The two functions alloca and allocaBytes allocate memory as malloc and mallocBytes do, but they pass a pointer to the allocate area to the functional passed as an argument and free the storage upon completion of that functional. If the Haskell system supports exceptions, the alloca family of functions is exception-safe, i.e., allocated memory is freed if an exception is thrown in the marshalling functional.