Valgrind显示的数据在构造函数c++中肯定丢失了

Valgrind showing data definitely lost in a constructor c++

本文关键字:c++ 显示 数据 构造函数 Valgrind      更新时间:2023-10-16

我正在尝试使用valgrind调试我的程序,以检查是否丢失了内存,并希望修复seg故障。Valgrind产生了以下输出,但当我检查代码中相应的行时,Valgrind指向的行只是在创建一个新对象。这是零件valgrind抱怨的程序:

相关valgrind输出:

--13598-- REDIR: 0x36fd4803d0 (free) redirected to 0x4a074f0 (free)
==13598== 
==13598== HEAP SUMMARY:
==13598==     in use at exit: 168 bytes in 1 blocks
==13598==   total heap usage: 31 allocs, 31 frees, 1,108 bytes allocated
==13598== 
==13598== Searching for pointers to 1 not-freed blocks
==13598== Checked 188,824 bytes
==13598== 
==13598== 168 bytes in 1 blocks are definitely lost in loss record 1 of 1
==13598==    at 0x4A06965: operator new(unsigned long) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==13598==    by 0x400F94: MLH<int>::MLH() (MLH.h:50)
==13598==    by 0x400C71: main (Benchmark.cpp:23)
==13598== 
==13598== LEAK SUMMARY:
==13598==    definitely lost: 168 bytes in 1 blocks
==13598==    indirectly lost: 0 bytes in 0 blocks
==13598==      possibly lost: 0 bytes in 0 blocks
==13598==    still reachable: 0 bytes in 0 blocks
==13598==         suppressed: 0 bytes in 0 blocks
==13598== 
==13598== ERROR SUMMARY: 7 errors from 5 contexts (suppressed: 2 from 2)

MLH.h:

template <typename T>
MLH<T>::MLH()
{
  proot = new HashNode<T>();
}

HashNode.h

template< typename T >
HashNode< T >::HashNode()
{
  for(int i=0; i<5; i++){
    keyArray[i] = -1;
    dataArray[i] = NULL;
    childArray[i] = NULL;
    //levelsArray[i] = 0;
  }
  for(int j = 0; j<9; j++ ){
    levelsArray[j] = 0;
  }
  levelsArray[0] = 1;
  numElements = 0;
  numChildren = 0;
  nodeLevel = 0;
  stemNode = 0;
  steps = 0;
  MLH_print_option = 0;
}
template <typename T>
MLH::~MLH()
{
    //delete proot
    for (int i=0; i< 5; i++) {
        if(proot->childArray[i] != NULL){
            delete proot->childArray[i];
        }
    }
}

当我尝试初始化HashNode对象时,我看到问题被调用了,但这对我来说没有意义。有什么我没有看到的吗?

template <typename T>
MLH::~MLH()
{
    //delete proot
    for (int i=0; i< 5; i++) {
        if(proot->childArray[i] != NULL){
            delete proot->childArray[i];
        }
    }
}

我看到上面的一些问题:

  • 您正在删除proot->childArray的元素,但没有删除proot本身。这是你的泄漏
  • 没有必要对null进行测试。只需要delete。将delete应用于空指针不会有任何作用
  • 为什么这个函数在文件HashNode.h