问题
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;
}
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.
The exact error I'm given is:
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)
Thanks for any help
回答1:
You are accessing n
after it has been deleted. That is causing undefined behavior.
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 delete
ing a nullptr
or else delete
ing a garbage pointer (depending on what n->next
on the end of the linked list points to).
来源:https://stackoverflow.com/questions/27323913/valgrind-8-bytes-inside-a-block-of-16-freed