How does OCaml's garbage collector handle external functions

If I write a C function and call it externally from OCaml code, and the C function makes a memory allocation, how does the garbage collector handle this? Does this memory need to be manually freed as it was manually allocated? And by extension, how do modules like the Array module in the standard library handle this exact problem without requiring arrays to be manually freed? Are they reference counted?

You need to use certain C macros (CAMLlocal, CAMLparam, etc) to register your allocated variables with the OCaml runtime. This is all nicely explained in the manual, see OCaml - Interfacing C with OCaml.


1 Like

It depends what kind of memory allocation you are talking about. If it is an allocation in the OCaml heap (e.g., caml_alloc_*), then it is handled like any other OCaml allocation; it will be collected once it is no longer reachable from the GC roots. If it is an allocation in the C heap (e.g., malloc), then it has to be manually handled. Presumably, this allocation will be referenced by a so-called “custom” block, so it is common practice to add a finalizer to this custom block which will be in charge of calling the deallocation function (e.g., free) when the custom block is no longer reachable from the GC roots.

1 Like