c++ - Valgrind 8 bytes inside a block of 16 free'd -
i'm writing code lab in class, exercise in ood design using circular linked list. means few key functions used aren't accessible me. however, i'm confused because although driver mimics 1 written professor, i'm still getting mchk error in title. here code 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 similar question problem i'm trying access memory has been freed. i.e. how can n = n->next if n doesn't exist anymore. tried switching while loop using current , next pointer, made problem worse. code works in professor's version of assignment, in haven't implemented functions need to.
the exact error i'm given is:
invalid read of size 8 @ 0x400d8a: main (lab04.cpp:28) // references loop address 0x5a02048 8 bytes inside block of size 16 free'd @ 0x4c28fac: operator delete(void*) 0x400d81: main (lab04.cpp:29)
thanks
you accessing n
after has been deleted. causing undefined behavior.
further, you're not checking n->next
valid: deleted head
in first iteration. deleting n
cause head
updated? if not, you'll reach undefined behavior again when reach end of linked list (which may caused either delete
ing nullptr
or else delete
ing garbage pointer (depending on n->next
on end of linked list points to).
Comments
Post a Comment