caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* [Caml-list] Memory leak in ocaml runtime with backtraces+threads?
@ 2016-04-11 11:27 Rob Hoes
  2016-04-11 12:01 ` Gabriel Scherer
  0 siblings, 1 reply; 3+ messages in thread
From: Rob Hoes @ 2016-04-11 11:27 UTC (permalink / raw)
  To: caml-list

Hello,

I have noticed that an OCaml program with backtrace recording enabled seems to leak memory each time a new thread is created and completes.

For example, the following program, compiled with the `-g` option, will very quickly eat up all your memory:

let _ =
  Printexc.record_backtrace true;
  let rec loop () =
    let t = Thread.create (fun () ->
      try
        raise Not_found
      with Not_found ->
        ()
    ) () in
    Thread.join t;
    loop ()
  in
  loop ()

I’ve tried this on various compilers (4.02.3, 4.01.0 and 3.12.1), on Linux and Mac, native and bytecode, and see the problem on all of them.

Valgrind reports that the allocation of `caml_backtrace_buffer` in the function `caml_stash_backtrace` in asmrun/backtrace_prim.c is the culprit (https://github.com/ocaml/ocaml/blob/trunk/asmrun/backtrace_prim.c#L98):

  if (caml_backtrace_buffer == NULL) {
    Assert(caml_backtrace_pos == 0);
    caml_backtrace_buffer = malloc(BACKTRACE_BUFFER_SIZE
                                   * sizeof(backtrace_slot));
    if (caml_backtrace_buffer == NULL) return;
  }

The `caml_backtrace_buffer` variable is a global variable initialised to NULL in byterun/backtrace.c. However, it seems to be local to a thread (how does it become thread local?), is set to NULL whenever a thread is created (where?), and a new malloc happens when an exception is raised. It is not freed when the thread completes.

Has anyone seen this before, or have suggestions for how to fix it?

Thanks,
Rob


^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2016-04-11 12:50 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2016-04-11 11:27 [Caml-list] Memory leak in ocaml runtime with backtraces+threads? Rob Hoes
2016-04-11 12:01 ` Gabriel Scherer
2016-04-11 12:48   ` Rob Hoes

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).