2012-05-12 84 views
4

由於memory pools(g_slice),我在我的代碼中獲得possibly lost。我的問題是:在代碼中有什麼可以做的事情來避免泄漏,或者這純粹是一個GLib問題?避免GLib內存池和Valgrind可能丟失在C

所有這些被報告爲'可能丟失'。

==2552== 
==2552== 744 bytes in 3 blocks are possibly lost in loss record 6 of 8 
==2552== at 0x40235BE: memalign (vg_replace_malloc.c:694) 
==2552== by 0x402361B: posix_memalign (vg_replace_malloc.c:835) 
==2552== by 0x408693E: ??? (in /usr/lib/libglib-2.0.so.0.1600.6) 
==2552== by 0x4088112: g_slice_alloc (in /usr/lib/libglib-2.0.so.0.1600.6) 
==2552== by 0x405B503: ??? (in /usr/lib/libglib-2.0.so.0.1600.6) 
==2552== by 0x804876C: add_inv (in /home/user/a.out) 
==2552== by 0x8048818: main (in /home/user/a.out) 

#include <glib.h> 
static GHashTable *hashtable1; 
static GHashTable *hashtable2; 

int add_inv (char *a, char *b) { 
    GHashTable *table = NULL; 
    gpointer old_value; 
    char *mykey = NULL; 
    int i, plus, *pointer; 

    for (i = 0; i < 2; i++) 
    { 
     if (i == 0) 
     { 
      table = hashtable1; 
      mykey = a; 
     } 
     else if (i == 1) 
     { 
      table = hashtable2; 
      mykey = b; 
     } 
     old_value = g_hash_table_lookup (table, mykey); 
     if (old_value != NULL) 
     { 
      pointer = (int *) old_value; 
      plus = *pointer + 10; 
     } 
     else 
     plus = 10; 

     pointer = g_malloc (sizeof (int)); 
     *pointer = plus; 
     g_hash_table_replace (table, g_strdup (mykey), pointer); 
    } 
} 

int main() { 
    int i; 
    hashtable1 = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, g_free); 
    hashtable2 = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, g_free); 

    for (i = 0; i < 20; i++) 
    { 
     char *a = g_strdup ("val1"); 
     char *b = g_strdup ("val2"); 
     add_inv (a, b); 
     g_free (a); 
     g_free (b); 
    } 
    g_hash_table_destroy (hashtable1); 
    g_hash_table_destroy (hashtable2); 
    return 0; 
} 

回答

2

集G_SLICE環境變量來重新配置Gslice上內存分配器。

G_SLICE=always-malloc ./your_application 

這裏是GLib documentation的相關部分。

這將導致通過g_slice_alloc()和 通過g_slice_free1發行分配的所有切片()通過直接調用 實際分配給g_malloc()和g_free()。這對於內存檢查器 以及類似的使用Bohem GC類似算法產生更準確結果的程序非常有用。它也可以與調試 系統的malloc實現的功能,如glibc的 MALLOC_CHECK_ = 2調試錯誤的片分配代碼,所有調試塊通常是一個更好的調試工具。

+0

我得到了那部分,但是,我很感興趣,看看我能不能在我的代碼中刪除它們,而不僅僅是當我執行程序時。 – user43092