Memory Leaks in GTK hello_world program

前端 未结 2 605
别跟我提以往
别跟我提以往 2020-12-04 01:49

So... I\'m trying to eliminate some memory leaks from my GTK+ 3 program. I though it would be a good idea to look back at some simple examples to see if there is some cleanu

相关标签:
2条回答
  • 2020-12-04 01:59

    This answer is compiled from answers to the same question (on the now defunct www.gtkforums.com).

    GTK+ is pretty lazy when it comes to allocating and deallocating internal buffers needed for the life time of the application. For example it may allocate an area of memory for a lookup table during initialisation which is needed for the life of the application. GTK+ will then never deallocate this. To Valgrind this looks like a memory leak, (which technically it is) but as an optimisation GTK+ does not deallocate it as it will be deallocated during application exit and so not an error. This is why you need suppression files so that Valgrind can ignore these. The problem is that you will need to change these with most GTK+ version changes.

    Repository of suppression files: https://github.com/dtrebbien/GNOME.supp

    After cloning the repository, you can generate the suppression files (also comes with glib, gdk, and others) with "make" and then refer valgrind to them like so:

    valgrind ./a --suppression=/path/to/gtk3.supp
    
    0 讨论(0)
  • 2020-12-04 02:00

    For debugging glib/gtk programs I would use this command:

    G_SLICE=debug-blocks valgrind --tool=memcheck --leak-check=full <gtk program>
    

    G_SLICE=debug-blocks will turn off gtk's advanced memory management to allow valgrind to show correct results.

    --leak-check=full will show stack traces for the leaked memory blocks.

    You can also use --show-reachable=yes to see stack traces for all memory blocks that haven't been free when the program exits.

    There is also the massif valgrind tool that tracks memory usage to show which parts of the program are using the most memory.

    Run program under massif:

    G_SLICE=always-malloc valgrind --tool=massif --detailed-freq=2 --max-snapshots=400 --num-callers=20 <gtk program>
    

    Show results:

    ms_print massif.out.<pid>
    
    0 讨论(0)
提交回复
热议问题