OCaml栈追踪在栈溢出时会被截断。例如,下面的程序会产生如下所示的栈追踪:
let rec f0 () = 1 + f1 ()
and f1 () = 1 + f2 ()
and f2 () = 1 + f3 ()
and f3 () = 1 + f4 ()
and f4 () = 1 + f5 ()
and f5 () = 1 + f5 ()
let _ =
Printexc.record_backtrace true;
f0 ()
Fatal error: exception Stack overflow
Raised by primitive operation at file "stackoverflow.ml", line 6, characters 20-25
Called from file "stackoverflow.ml", line 6, characters 20-25
…
Called from file "stackoverflow.ml", line 6, characters 20-25
与错误不是堆栈溢出时的堆栈跟踪相比(将最后一个
f5()
更改为failwith "Oops"
),请查看以下内容:Fatal error: exception Failure("Oops")
Raised at file "pervasives.ml", line 30, characters 22-33
Called from file "stackoverflow.ml", line 6, characters 20-35
Called from file "stackoverflow.ml", line 5, characters 20-25
Called from file "stackoverflow.ml", line 4, characters 20-25
Called from file "stackoverflow.ml", line 3, characters 20-25
Called from file "stackoverflow.ml", line 2, characters 20-25
Called from file "stackoverflow.ml", line 1, characters 20-25
Called from file "stackoverflow.ml", line 10, characters 2-7
如何防止 OCaml 截断堆栈跟踪?