gpt4 book ai didi

c++ - 大小为 8 的 Valgrind 无效读取 C++

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

Valgrind 中的这个错误是什么意思?我看了很多其他帖子,但我仍然不明白错误的实际含义。我的 Dragon 析构函数有问题吗?

==48500== Invalid read of size 8
==48500== at 0x40AF66: Dragon::~Dragon() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test)
==48500== by 0x40AFDB: Dragon::~Dragon() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test)
==48500== by 0x406841: Floor::deleteAll() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test)
==48500== by 0x4022D8: Floor::~Floor() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test)
==48500== by 0x401EE1: main (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test)
==48500== Address 0x5a1d130 is 0 bytes inside a block of size 40 free'd
==48500== at 0x4C2A4BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==48500== by 0x40A7B3: Treasure::~Treasure() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test)
==48500== by 0x40671B: Floor::deleteAll() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test)
==48500== by 0x4022D8: Floor::~Floor() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test)
==48500== by 0x401EE1: main (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test)

编辑:这就是我的 Dragon 类的样子:

#include "dragon.h"
#include <iostream>
#include <cmath>
#include <cstdlib>

using namespace std;

Dragon::Dragon(Item *hoard) {
// initalizes some variables
treasureHoard = hoard;
}

Dragon::~Dragon(){
treasureHoard->deadDragon();
}

// some functions

编辑:基本上我的代码是这样做的:

D *ptr=new D();
// some code …
if (ptr->isDead()) {
delete ptr;
ptr = NULL;
}
// some code

// at the end of the program:
if (ptr) { // <<< is this causing the error?
delete ptr;
ptr = NULL;
}

最佳答案

我认为 valgrind 消息非常清楚:

==48500==  Address 0x5a1d130 is 0 bytes inside a block of size 40 free'd

有一个数据 block 被“释放”(在 C++ 中很可能实际被“删除”)并且仍在被访问。更准确地说,正在读取大小为 40 的已释放内存块开头的一个 8 字节字。

也就是说,您有效地让代码执行与此等同的道德操作:

T* ptr = new T; // allocator memory of an object of size 40
...
delete ptr; // release the memory
...
X value = ptr->start; // read the first word of the data

(很明显,类型、成员和变量名称在代码中会有所不同,但大致就是这样)

这是一个复制问题的完整程序(尽管堆栈更简单):

struct foo {
double values[5];
};

int main()
{
foo* ptr = new foo();
delete ptr;
double x = ptr->values[0];
return x;
}

关于c++ - 大小为 8 的 Valgrind 无效读取 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27204658/

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