Valgrind在16个块中释放了8个字节 [英] Valgrind 8 bytes inside a block of 16 free'd

查看:114
本文介绍了Valgrind在16个块中释放了8个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为课堂上的实验室编写代码,这是使用循环链表进行OOD设计的练习.这只是意味着我无法使用一些关键功能.但是,我最困惑的是,尽管我的司机模仿了教授写的那个,但我仍然在标题中遇到mchk错误.这是它引用的代码

I'm writing code for a lab in class, which is an exercise in OOD design using a circular linked list. This just means that a few key functions that are used aren't accessible to me. However, I'm mostly confused because although my driver mimics the one written by the professor, I'm still getting the mchk error in the title. Here is the code it references

{
int nNodesFreed{0};
node* n{head};

for(; n!= head || ! nNodesFreed; n = n->next) {
    delete n;
    nNodesFreed++;
    }
cout << "# nodes freed: " << nNodesFreed << endl;
}

我在一个类似的问题中看到问题可能出在我试图访问已经释放的内存上. IE.如果n不再存在,那么n = n-> next怎么办.我尝试使用当前和下一个指针切换到while循环,但这使问题更加严重.该代码可以在我教授的作业版本中完美运行,在该版本中,我没有实现所需的功能.

I saw in a similar question that the problem could be that I'm trying to access memory that has already been freed. I.E. how can n = n->next if n doesn't exist anymore. I tried switching to a while loop using a current and a next pointer, but that made the problem even worse. The code works perfectly in my professor's version of the assignment, in which I haven't implemented the functions that I need to.

我给出的确切错误是:

Invalid read of size 8 
  at 0x400D8A: main (lab04.cpp:28) // this references the for loop
Address 0x5a02048 is 8 bytes inside a block of size 16 free'd
  at 0x4C28FAC: operator delete(void*) 
  by 0x400D81: main (lab04.cpp:29)

感谢您的帮助

推荐答案

删除n后,您将对其进行访问.这会导致未定义的行为.

You are accessing n after it has been deleted. That is causing undefined behavior.

此外,您并没有检查n->next是否有效:您在第一次迭代中删除了head.删除n是否会导致head被更新?如果不是,那么到达链接列表的末尾时,您将再次遇到未定义的行为 (可能是由于delete插入nullptrdelete插入了垃圾引起的)指针(取决于链接列表末尾的n->next指向什么).

Further, you're not checking for n->next to be valid: you deleted head in the first iteration. Does deleting n cause head to be updated? If not, then you'll reach undefined behavior again when you reach the end of the linked list (which may be caused either by deleteing a nullptr or else deleteing a garbage pointer (depending on what n->next on the end of the linked list points to).

这篇关于Valgrind在16个块中释放了8个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆