Where does the GHC allocate foreign memory and how does the garbage collector do this?

This question is about the alloca and malloc functions from Foreign.Marshal.Alloc and newForeignPtr and mallocForeignPtr from Foreign.ForeignPtr . Where is the allocated memory located and how does the garbage collector relate to it?

+7
garbage-collection memory-management haskell ghc
source share
3 answers

malloc calls C malloc() , so it allocates memory on the C heap, which you must free manually. (You can also do this with C with free() if you want.)

alloca and mallocForeignPtr allocate pinned byte arrays that live on a Haskell pinned heap. The GC will automatically release them when they are no longer needed, but will never move them (since they are pinned), so you can pass their addresses to C.

newForeignPtr not relevant to your question.

+3
source share

The memory pointed to by Ptr a allocated by malloc lives on the heap, as in the C programming language. It is ignored by the garbage collector - you must manually free it yourself using free , and be careful not to use it again after that.

alloca f performs a similar distribution, calls f with a pointer, and frees memory after that. Pointer should not be used after return f .

These routines are not intended to be used in everyday code, but only to interact with other languages ​​using a C-like interface (FFI). You get exactly the same guarantees of memory security. Sentence C - which has virtually no. Thus, it is quite dangerous and should be used with great care.

For comparison, memory marked ForeignPtr is still stored in the heap, but garbage will be collected after there are no more pointers (i.e. Haskell ForeignPtr a ) to memory. Please note that even if garbage collection is used here, such pointers are not risk-free. Indeed, when Haskell no longer has pointers to live memory, the runtime will free it, even if that pointer still lives in a foreign language. The programmer must make sure that this never happens.

+6
source share

Everyone allocates dynamic memory, and it is on the heap.

Odd - malloc ; the memory allocated by malloc must be EXPLICITELY freed.

alloca allocates temporary dynamic memory and passes it to the calculation. the memory will be automatically freed when the calculation is completed.

mallocForeignPtr allocates memory and returns an external pointer. The memory is freed automatically when the pointer is discarded.

newForeignPtr adds a new reference to existing dynamically allocated memory. The memory will be freed ONLY when the LAST reference to the object is down.

If you know C ++: malloc is naked new , malloca is unique_ptr/auto_ptr , mallocForeignPtr and newForeignPtr are shared_ptr .

+1
source share

All Articles