Bug in destructor of doubly linked list (C++)
The memory issue is likely here from the look of it:
void List4::Delete(int pos) { doubleNode* ptrA = FindPosition(pos)->prev; doubleNode* ptrB = ptrA->next->next; ptrB->prev = ptrA; ptrA->next = ptrB; // After this point, ptrA->next points to what used to be ptrA->next->next length--; delete ptrA->next; // So when this delete executes on ptrA->next, it deletes the pointer behind the target // also after ptrA->next is re-assigned there is no longer a reference to the original ptrA->next so thats a memory leak }
Also, be careful using 1 indexing for your container. For example, as written, it looks like you're going to dereference a null pointer if you tried to delete an item at pos = 0, and most programmers will think of pos 0 as the start, not pos 1.
Also also, try to get in the habit of using nullptr instead of NULL when possible. It's a best practice in modern C++ for type safety. As an example, lets say you have a function foo with 2 overloads, an int and a pointer type:
void foo(int i); void foo(char* c);
foo(NULL) and foo(nullptr) would call different overloads since NULL is just a macro for an int, even though both are "null pointer" representations.
EDIT: also, i'm confused at the attempt to get O(1) time during destruction, as you are still having to delete n elements. I don't think that's possible since you can't "batch delete" in C++ AFAIK. You're essentially trying to traverse an array of n elements in O(1) time...
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now