Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Caml-Exceptions from C-Code and handlingh of Caml-allocations
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2008-01-18 (11:12)
From: Richard Jones <rich@a...>
Subject: Re: [Caml-list] Caml-Exceptions from C-Code and handlingh of Caml-allocations
On Thu, Jan 17, 2008 at 10:10:50PM +0100, Oliver Bandel wrote:
> when throwing Caml-exceptions from C-Code,
> it's clear to me to deallocate C-allocated stuff by myself,
> as I would do in pure C applications also.

Anything allocated using malloc (ie. on the C heap) you must take care
to free.  Most external C libraries that you call will allocate stuff
like that and so you must free it too, in a way that will depend on
the particular C library.  One way to do this is to wrap the pointer
in an OCaml value and attach a finalizer to it.  The finalizer is
called when there are no more OCaml references around, so you can free
the pointer then ... but be careful in case there are still references
held in C code.

Take a look at the function Val_connect here:;file=libvirt/libvirt_c.c

> But will throwing Caml-exceptions from C automatically free
> the CAML<something> / caml_alloc allocated stuff?
> (This is what I would expect, but I'm not sure on that.)

Yes - values allocated either from OCaml or in C using caml_alloc /
caml_copy_* etc, are allocated on the OCaml heap and deallocated by
the garbage collector when they are no longer referenced.  In other
words you don't have to worry about them.


Richard Jones
Red Hat