Is it safe to hold onto string data in C bindings?

The OCaml C binding documentation says that you need to copy any string parameters before releasing the runtime lock.

Am I correct in assuming that this is a generalization of a rule that you shouldn’t hold onto the result of String_val after any function that could allocate? i.e. this is also bad:

value example(value vbar)
  const char* bar = String_val(vbar);
  vfoo = caml_copy_string("example");
  printf("%s\n", bar); // bad, vbar's data might have moved?

(I’m working on a blog post about problems I ran into with C bindings and want to make sure everything is accurate)

1 Like

Yes, you are correct.

Is he? CAMLparam1(vbar) is supposed to protect the variable vbar until CAMLreturn (or the runtime lock is released).

My understanding is that these macros are used to register the local roots with the GC so they can be found and updated when the GC moves the value they point to, but by themselves they don’t keep their values from being moved.

1 Like

Yes: as a result it’s still safe to access the string through vbar after the call to caml_copy_string. But bar isn’t protected, so it’s not safe to access the string through bar.


Thanks for the precisions. @BrendanLong In addition to a post, I think clarifications and examples should be added to the manual.


Great, thanks for the information everyone!

Yeah, that makes sense. I think I’ll see if I can clarify the manual at all, and also make a blog post (it can’t hurt to have more info available when people search for their error messages).

1 Like

I’ve been super busy for a while, but here’s the blog post:

(And the code I was working on when I wrote this will show up in our Mssql library as soon as I have time)