views:

21

answers:

3

Hello,

I have a function for loading GdkPixbufAnimation from stream.

GdkPixbufAnimation* load_image_from_stream(GInputStream* input_stream, GCancellable* generator_cancellable)
{ 
   GError** error; 
 gboolean res;
 gssize n_read;
 guchar buffer[65535];

 GdkPixbufAnimation* animation;
 GdkPixbufLoader*    loader;

 loader = gdk_pixbuf_loader_new();

 res = TRUE;

 while (1)
 {
      n_read = g_input_stream_read (input_stream, buffer, sizeof (buffer), generator_cancellable, error);

   if (n_read < 0)
   {
    res = FALSE;
    error = NULL; 
    g_object_unref(loader);
      break;
   }

   if (n_read == 0)
   {
      break;
    g_object_unref(loader);
   }

   if (!gdk_pixbuf_loader_write (loader, buffer, n_read, error))
   {
    res = FALSE;
    error = NULL;
    g_object_unref(loader);
    break;
   }
 }

 if (!gdk_pixbuf_loader_close (loader, error)) 
 {
  res = FALSE;
  error = NULL;
  return;
 }

 animation = NULL;

 if (res) 
 {
  animation = gdk_pixbuf_loader_get_animation(loader);

  if (animation)
  {
   g_object_ref (animation);
      g_object_unref(loader);
  }
 }

 return animation;
}

Try to call this functio so:

void loading(JobParam* param)
{   
    GInputStream* input_stream;
    input_stream = g_file_read(param->file, param->generator_cancellable, NULL);
    param->animation = load_image_from_stream(G_INPUT_STREAM(input_stream), param->generator_cancellable);  

    g_input_stream_close(input_stream, param->generator_cancellable, NULL);
    g_object_unref (input_stream);
}

But when i try to call this function i have mem leak. Why? What's wrong in function implementation?

Thank you

+1  A: 

Are statements in if block in right order?

 if (n_read == 0)
   {
      break;
      g_object_unref(loader);
   }
Pmod
+1  A: 
  • Your indentation (or lack thereof) makes the code impossible to read. Fix that, and the errors will probably be more obvious.
  • You have unreachable code in if (n_read == 0), right after that break statement.
  • You appear to be inconsistent in free-ing loader.
  • error in never initialized, but is passed to gdk_pixbuf_loader_new.
Thanatos
+1  A: 

After the condition if (n_read == 0) You have provided a break first. Hence the loaded pixbuff is not freed. So you are getting a memory leak.

Additional points:

You pass a double pointer namely error to the function

g_input_stream_read 

This pointer will have the error code and error string loaded into it if there is a error in the API. Please check it before assigning that to NULL. You can probably check the structure definition of GError here. GError Please check the value of code and message to get description on the error.

This has to be done for all the other API calls as well. Hope that helps.

Praveen S