Re: problem with memory leaks
- From: "David Necas (Yeti)" <yeti physics muni cz>
- To: morph_in <atandon_b03 iiita ac in>
- Cc: gtk-list gnome org
- Subject: Re: problem with memory leaks
- Date: Mon, 3 Apr 2006 14:06:41 +0200
On Mon, Apr 03, 2006 at 03:19:25AM -0700, morph_in wrote:
> 
>    I am a newbie to GTK programming and cannot work out a simple problem ,so
> pls can some one inform abt the problem
> 
> GtkTextBuffer *tbuffer;
>     GtkTextIter start;
> 	GtkTextIter end;
> 	GtkWidget * textv = lookup_widget(GTK_WIDGET(menuitem), "textview1");
> 	tbuffer =gtk_text_view_get_buffer(textv);
> 	FILE *infile;
>     infile = fopen("/root/Desktop/a.s", "r");
>      if (infile)
>       {
>         char buffer[1024];
>         int nchars;
>         gchar *utf8;
>         while (1)
>           {
>             nchars = fread(buffer, 1, 1024, infile);
>             utf8 = g_locale_to_utf8(buffer, nchars, NULL, NULL, NULL);
This always allocates a new string...
>            if (!utf8)
>               { return;
>              }
>             gtk_text_buffer_get_end_iter(tbuffer, &end);
>             gtk_text_buffer_insert(tbuffer, &end, utf8, strlen(utf8));
> 
>             if (nchars < 1024)
>                 break;
>           }
>         fclose (infile);
> 		  free(utf8);
...so freeing it only once does not work.
Moreover, if the locale encoding is not single-byte (e.g.,
it is already UTF-8), this does not work because nothing
guarantees characters won't be split by the 1024-byte
boundaries.
Moreover, if the file is not really huge (and in that case
you would have other scalability problems with this code),
it is much better to use g_file_get_contents().
>       }
>     gtk_text_view_set_buffer(GTK_TEXT_VIEW(textv), tbuffer);
This is pointless, as tbuffer is still the same object as
before, that is, it is still the text buffer of textv.
> 		
> //g_free(tbuffer);                         //freeing any of them produces
> segmentation fault 
> 	 //g_free(textv);                   //and if i donot free them then i get a
> 15Kb leak 
References to objects are released with g_object_unref(),
please see some intro (the description is in a lot of
places, althout I cannot recommend any particular).
However, since this piece of code seems to *not* own any
reference to the objects, it should not release any either.
Yeti
--
That's enough.
[
Date Prev][
Date Next]   [
Thread Prev][
Thread Next]   
[
Thread Index]
[
Date Index]
[
Author Index]