使用valgrind调查Glib内存泄漏

时间:2013-01-28 13:34:19

标签: c++ glib

我知道此前有关于此问题的类似线程,并且在此网站https://live.gnome.org/Valgrind已经解释过,我在下面写了我的简单程序

  #include <glib.h>
  #include <glib/gprintf.h>
  #include <iostream>

  int main()
 {
const gchar *signalfound = g_strsignal(1);
std::cout <<  signalfound<< std::endl;
return 0; 
  }

但是当我尝试使用此命令使用valgrind进行检查时      G_DEBUG = gc-friendly G_SLICE = always-malloc valgrind --leak-check = full --leak-resolution = high ./g_strsignal

这是结果

   ==30274== Memcheck, a memory error detector
   ==30274== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
   ==30274== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
   ==30274== Command: ./g_strsignal
   ==30274== Parent PID: 5201
   ==30274== 
   ==30274== 
   ==30274== HEAP SUMMARY:
   ==30274==     in use at exit: 14,746 bytes in 18 blocks
   ==30274==   total heap usage: 24 allocs, 6 frees, 23,503 bytes allocated
   ==30274== 
   ==30274== LEAK SUMMARY:
   ==30274==    definitely lost: 0 bytes in 0 blocks
   ==30274==    indirectly lost: 0 bytes in 0 blocks
   ==30274==      possibly lost: 0 bytes in 0 blocks
   ==30274==    still reachable: 14,746 bytes in 18 blocks
   ==30274==         suppressed: 0 bytes in 0 blocks
   ==30274== Reachable blocks (those to which a pointer was found) are not shown.
   ==30274== To see them, rerun with: --leak-check=full --show-reachable=yes
   ==30274== 
   ==30274== For counts of detected and suppressed errors, rerun with: -v
   ==30274== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

我注意到valgrind所说的“Reachable blocks(找到指针的那些块)没有显示。”然后我尝试检查gmem.c 因为我使用了glib-2.35.4版本,所以对应函数的来源。我找到了以下代码

   gpointer
   g_malloc (gsize n_bytes)
   {
      if (G_LIKELY (n_bytes))
         {
              gpointer mem;

               mem = glib_mem_vtable.malloc (n_bytes);
               TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
               if (mem)
              return mem;

               g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
                G_STRLOC, n_bytes);
           }

       TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));

   return NULL;
  }

我的问题是

  1. 这仍然是正常情况,valgrind曾说过“Reachable blocks(找不到指针的那些)。”,我认为这句话是指上面的g_malloc函数,其中有返回mem一个gpointer变量?

  2. 如果没有任何替代方案可以解决,“仍然可以达到:18个街区中的14,746个字节”在valgrind上面说过了什么?

  3. 我正在运行x86 fedora 18 谢谢

1 个答案:

答案 0 :(得分:1)

它很可能是指函数g_strsignal()返回的动态分配的内存 valgrind说“Reachable blocks ....”,因为有效指针(signalfound)仍然指向动态分配的内存。
如果Valgrind发现指向动态内存的指针丢失(覆盖),那么它会报告“明确泄漏...”,因为它可以最终说出动态永远不会释放内存块。在你的情况下,指针仍指向块valgrind不会认为它已丢失但它假定它可能是设计的。