Skip to content

Instantly share code, notes, and snippets.

@keigoi
Last active December 26, 2015 20:29
Show Gist options
  • Save keigoi/7208381 to your computer and use it in GitHub Desktop.
Save keigoi/7208381 to your computer and use it in GitHub Desktop.
OCaml fails with SEGV instead of exception Stack_overflow
(*
OCaml fails with SEGV instead of exception Stack_overflow
- by Keigo IMAI <keigo.imai@gmail.com>
ocamlopt -g -thread -I +threads unix.cmxa threads.cmxa segv_stackovfl.ml -o a.out
ulimit -s 8192
./a.out 540000
*)
let rec run_forever x =
List.iter (fun () -> x) []; (* alloc closure to ensure context switching *)
run_forever ()
let stack_eater limit =
let rec loop i =
if i<limit then begin
loop (i+1); (* non tail-call *)
ignore ();
end else begin
run_forever (); (* stack is almost full. now run into infinite context-switching (which will cause SEGV) *)
end
in
loop 0
(* search for (stack limit) - 32k *)
let rec loop i =
begin try
stack_eater i
with
| Stack_overflow ->
Printf.fprintf stderr "Stack overflow at loop limit %d. try next!\n" i;
end;
loop (i-50)
let loop_count = int_of_string (Sys.argv.(1))
;;
(* run another thread to enable context switching *)
Thread.create (fun () -> ()) ()
;;
loop loop_count
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment