Re: memory leak, destroying widgets

Jacques Garrigue <[email protected]>
Newsgroups gmane.comp.lang.ocaml.lib.gtk
Message-ID <[email protected]>
From: "Jacques Le Normand" <[email protected]>

> I'm getting a memory leak in my program because, when I destroy a widget,
> the memory does not get freed. I thought it would be done automatically when
> I call #remove from the container, but this does not seem to be the case.
> How can I destroy my widgets and make sure the memory is cleared? I've tried
> 2 or 3 different ways, with the same result.

You should use Gc.full_major, to ensure that all finalizers are
called.
Note however that, in byte code, a variable referenced in the
environment (either function argument or let-definition) cannot be
freed until you leave the function.
It should be ok to add a Gc.full_major call in your timeout.

Jacques


> Here is a program that creates and destroys 100 GEdit.entry every 200ms. At
> every iteration, I call  Gc.allocated_bytes . The number printed keeps going
> up (showing that there is a memory leak.) I posted it a week ago. I've
> gotten a couple of people to run it and they all get the same result. If
> more people could run it to make sure, that would be greatly approciated.
> cheers
> --Jacques
> 
> 
> let repeat n f =
>   let rec rep i =
>     if i = n then [] else (f () :: rep (i+1))
>   in
>     rep 0
> 
> 
> let container_clear c =
>   List.iter c#remove c#all_children
> 
> let _ =
>   let source_window = GWindow.window ~width:100 ~height:100 () in
>   let vbox = GPack.vbox ~packing:source_window#add () in
>   let inside = ref false in
>   let fill_vbox () =
>     if !inside then
>       ()
>     else
>       begin
>     inside := true;
>     let add_entry () =
>       let ret = GEdit.entry ()
>       in
>         vbox#pack (ret:>GObj.widget);
>         ret
>     in
>       container_clear vbox;
>       print_endline (string_of_float  (Gc.allocated_bytes ()));
>       ignore(repeat 100 add_entry);
>       inside:=false
>       end
>   in
>     ignore(Glib.Timeout.add 200 (fun () -> fill_vbox (); true));
>     source_window#show ();
>     GMain.Main.main ()
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.