# OCaml string handling in C stubs

**URL:** <https://discuss.ocaml.org/t/ocaml-string-handling-in-c-stubs/628>\
**Category:** Learning\
**Created:** [July 25, 2017, 4:21pm UTC](https://discuss.ocaml.org/t/ocaml-string-handling-in-c-stubs/628 "2017-07-25T16:21:29Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![gndl](https://avatars.discourse-cdn.com/v4/letter/g/58f4c7/32.png) [@gndl](https://discuss.ocaml.org/u/gndl)\
**Post date:** [July 25, 2017, 4:21pm UTC](https://discuss.ocaml.org/t/ocaml-string-handling-in-c-stubs/628/1 "2017-07-25T16:21:29Z")

</div>

I am a little bit puzzled by the reference manual concerning the handling of OCaml strings in C stubs (§ 18.11.2) :

```auto
/* Copy the string argument to a C string, allocated outside the
OCaml heap. */
name = caml_stat_alloc(caml_string_length(vname) + 1);
name = caml_strdup(String_val(vname));

```

Can i simply use strdup like below ?

```auto
char * name = strdup(String_val(vname));

```

---

<div class="post-metadata">

**Author:** ![dbuenzli](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/dbuenzli/32/18_2.png) [@dbuenzli](https://discuss.ocaml.org/u/dbuenzli)\
**Post date:** [July 25, 2017, 4:39pm UTC](https://discuss.ocaml.org/t/ocaml-string-handling-in-c-stubs/628/2 "2017-07-25T16:39:44Z")

</div>

> [@gndl](#):
>
> Can i simply use strdup like below ?
> 
> char \* name = strdup(String\_val(vname));

No because OCaml strings can contain NULL bytes, which would confuse `strdup`. See the description of `String_val` in [the manual](http://caml.inria.fr/pub/docs/manual-ocaml/intfc.html#sec418).

---

<div class="post-metadata">

**Author:** ![gndl](https://avatars.discourse-cdn.com/v4/letter/g/58f4c7/32.png) [@gndl](https://discuss.ocaml.org/u/gndl)\
**Post date:** [July 25, 2017, 4:49pm UTC](https://discuss.ocaml.org/t/ocaml-string-handling-in-c-stubs/628/3 "2017-07-25T16:49:56Z")

</div>

Thank’s for your response.  
Does the function caml\_strdup skip null characters so that the string can be interpreted correctly in C?

---

<div class="post-metadata">

**Author:** ![dbuenzli](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/dbuenzli/32/18_2.png) [@dbuenzli](https://discuss.ocaml.org/u/dbuenzli)\
**Post date:** [July 25, 2017, 6:47pm UTC](https://discuss.ocaml.org/t/ocaml-string-handling-in-c-stubs/628/4 "2017-07-25T18:47:38Z")

</div>

No. If you follow the definition you’ll see that it ends up with [a memcpy](https://github.com/ocaml/ocaml/blob/5cb2b6ac514f4c94ce060f466fd8f5b80a6298c9/byterun/memory.c#L916). Recent compilers allow to check if the string is C safe with [this function](https://github.com/ocaml/ocaml/blob/5cb2b6ac514f4c94ce060f466fd8f5b80a6298c9/byterun/caml/mlvalues.h#L257) in `mlvalues.h`.
