开发者

Mem leak in image loader

开发者 https://www.devze.com 2023-01-06 14:33 出处:网络
I have a function for loading GdkPixbufAnimation from stream. GdkPixbufAnimation* load_image_from_stream(GInputStream* input_stream, GCa开发者_高级运维ncellable* generator_cancellable)

I have a function for loading GdkPixbufAnimation from stream.

GdkPixbufAnimation* load_image_from_stream(GInputStream* input_stream, GCa开发者_高级运维ncellable* 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


Are statements in if block in right order?

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


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.


  • 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.
0

精彩评论

暂无评论...
验证码 换一张
取 消