使用valgrind调查的Glib内存泄漏

Glib memory leak using valgrind investigation

本文关键字:内存 泄漏 Glib valgrind 调查 使用      更新时间:2023-10-16

我知道之前有关于这个问题的类似线程,在这个网站上 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友好型G_SLICE=始终马尔洛克瓦尔格林德 --泄漏检查=完全 --泄漏分辨率=高./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 说"未显示可到达的块(找到指针的块)。 然后我尝试检查 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说"未显示可到达的块(找到指针的块)"的正常情况吗,我认为这句话指的是上面的g_malloc函数,其中返回mem是一个gpointer 变量?

  2. 如果没有其他方法可以解决,"仍然可以到达:14,746 个块中的 18 个字节",关于 valgrind 上面所说的?

我正在运行 x86 软呢帽 18谢谢

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