If you use Obj.magic, or if you have buggy libraries which use Obj.magic (cough Extlib cough), then sometimes you’ll end up corrupting the OCaml heap. An easy way to track these problems down is to add this checkpoint function near the top of your code:
let checkpoint p = Gc.compact (); prerr_endline ("checkpoint at position " ^ p)
then place calls to
checkpoint "A"; (
checkpoint "B" etc) around suspect code.
The checkpoint function does two things:
Gc.compact () does a full major round of garbage collection and compacts the heap. This is the most aggressive form of GC available, and I’ve found that it’s highly likely to segfault if the heap is corrupted. The second statement,
prerr_endline, prints a message to stderr and crucially also flushes stderr, so you’ll see the message printed immediately.
So the effect is that if the checkpoint function prints something, you can be very sure that your heap is not corrupt at that point in the program.
By placing these in and around suspect code, you can quickly narrow down the place where corruption happens.