gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:34:08 25 4
gpt4 key购买 nike

我正在尝试使用 valgrind 调试我的程序以检查是否丢失了我的内存并希望修复段错误。 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>();
}

哈希节点.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 应用于空指针不会执行任何操作。
  • 为什么这个函数在文件 HashNode.h 中?

关于c++ - Valgrind 显示数据肯定在构造函数 c++ 中丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23462888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com