2

Valgrind reports a memory leak when I run this simple test program:

#include <gdk-pixbuf/gdk-pixbuf.h>
int main() {
    GdkPixbuf* buf;
    GError* err = NULL;
    buf = gdk_pixbuf_new_from_file("test.jpg", &err);
    g_assert_no_error(err);
    g_object_unref(buf);
    return 0;
}

I'm aware of the issues regarding Valgrind and GLib/GDK/GTK, and of the several StackOverflow answers (such as this one, this other one, and others) regarding this issue.

For GLib it's enough to prefix the valgrind command with G_DEBUG=gc-friendly G_SLICE=always-malloc (though I still have some "still reacheable" leaks, which I ignore if they come from GLib).

However, with this small program I get a lot of "possibly lost" leaks. I have also tried other prefixes, such as G_DEBUG=resident-modules (suggested here) and G_SLICE=debug-blocks (suggested here), but the "possibly lost" leaks remain. I also tried several of the GNOME suppressions, namely the GDK one, but to no avail.

My question is: is my only alternative to create a suppression file for this case or is something wrong with the code?

The program was compiled with:

gcc -Wall -std=c99 -g -pedantic `pkg-config --cflags glib-2.0 gdk-pixbuf-2.0` pixbuf.c -o pixbuf `pkg-config --libs glib-2.0 gdk-pixbuf-2.0`

I'm using GDK-Pixbuf 2.30.7 (Ubuntu 14.04).

Thanks in advance.

4

2 回答 2

1

我看到的所有“可能丢失”的块都来自使用 GObject 注册类型时。这些确实仍然可以访问,只是 valgrind 不知道如何访问它们(诚然这有点奇怪,我不怪 valgrind 感到困惑),所以它报告它们为“可能丢失”而不是“仍然可达”。

您的代码没有任何问题,glib 中也没有真正的泄漏。您应该使用抑制文件。

于 2014-10-27T02:55:52.907 回答
0

如果 gdk_pixbuf_new_from_file() 由于某种原因(例如文件不存在)失败,“buf”将被赋值为 NULL,错误将通过“err”返回。然后 g_assert_no_error(err) 将终止程序,但它不会释放“err”指向的内存。如果您自己管理错误并使用 g_free_error(err) 释放“err”,您会做得更好。在调用“gdk_pixbuf_new_from_file”之后,删除其余代码,用以下代码替换它,看看你从 Valgrind 得到了什么:

if (!buf) {
    g_printerr("%s\n", err->message);
    g_free_error(err);
}
else {
    g_object_unref(buf);
}

顺便说一句,我对 Valgrind 不是很熟悉,我只是指出可能存在的内存泄漏。尽管此时您的程序将终止,并且内核可能足够聪明,可以回收它分配给程序的内存块。

于 2014-10-24T21:17:26.370 回答