How can I return early from a function?
Raise an exception. It's probably much more efficient than you expect.Example from discuss.ocaml Q&A:
let f x y z =
let exception Return of int in
try
if x = 1 then raise (Return 0);
if y = 2 then raise (Return 1);
z
with Return x -> x
Can I generate a segfault in OCaml?
No. For example, given
(* segfault.ml *)
external segfault : unit -> unit = "segfault"
let () = segfault ()
/* segfault_helper.c */
#include <caml/mlvalues.h>
#include <caml/bigarray.h>
CAMLprim value segfault(value unit) {
int *p = 0;
*p=1;
return unit;
}
This does not demonstrate a segfault in OCaml:
$ gcc -I$(opam var lib)/ocaml -c -fPIC segfault_helper.c $ ocamlopt -o segfault segfault.ml segfault_helper.o $ ./segfault Segmentation fault (core dumped)
Because that's not OCaml. That's OCaml and C.
Likewise this does not demonstrate a segfault in OCaml:
$ ocaml OCaml version 5.4.0 Enter #help;; for help. # print_endline (Obj.magic 100);; Segmentation fault (core dumped)
Because that's not OCaml. That's OCaml and the OCaml compiler implmentation.
By the way, it's not important for the C file to be named _helper, but it can't share the name of the .ml file, or you'll get a bunch of linking errors like:
:(.data+0x28): multiple definition of `camlSegfault.data_end'; segfault.o::(.data+0x28): first defined here /usr/bin/ld: segfault.o: in function `camlSegfault.data_end': :(.data+0x30): multiple definition of `camlSegfault.frametable'; segfault.o::(.data+0x30): first defined here