这不是具有相似名称的问题的重复,这涉及 OOP 以及 new 和 delete 调用。
我正在尝试编写一个函数,该函数将迭代到我的链表的后面,然后删除最后一个节点堆中分配的内存。
这是我的代码:
void LinkedList::delete_back(){
if(head != NULL){
ListNode *end = head;
while(end->next != NULL)
end = end->next;
delete end;
}
size--;
}
这是我的类定义:
class ListNode{
public:
Item data;
ListNode *next;
};
class LinkedList{
private:
ListNode *head;
int size;
public:
LinkedList();
~LinkedList();
bool empty();
void insert_front(Item i);
void insert_back(Item i);
void delete_front();
void delete_back();
void print();
};
Andddddd .....这是问题所在,我收到来自 valgrind 的类似这样的错误消息的垃圾邮件,其中一些声明大小为 4 的无效读取,另一些声明大小为 8 的无效读取:
==4385== Invalid read of size 4
==4385== at 0x400CAA: LinkedList::print() (in /home/jon/jball2_lab06/linkedlist)
==4385== by 0x400EDD: main (in /home/jon/jball2_lab06/linkedlist)
==4385== Address 0x5a04f30 is 0 bytes inside a block of size 16 free'd
==4385== at 0x4C2A4BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4385== by 0x400C5E: LinkedList::delete_back() (in /home/jon/jball2_lab06/linkedlist)
==4385== by 0x400E99: main (in /home/jon/jball2_lab06/linkedlist)
如果有帮助,我会发布其余的错误,但除非我需要,否则我不想在 50 行上击中 4 次空格。有谁知道这可能是什么?我究竟做错了什么?
更新------------------------ 我已将代码编辑为:
void LinkedList::delete_back(){
if(head != NULL){
ListNode *end = head;
ListNode *prev_end;
while(end->next != NULL){
prev_end = end;
end = end->next;
}
prev_end->next = NULL;
if(end != NULL) delete end;
size--;
}
}
我现在越来越多地读取大小为 8/4 的错误和无效的免费/删除错误
==5294== Invalid free() / delete / delete[] / realloc()
==5294== at 0x4C2A4BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
和这个:
==5294== Use of uninitialised value of size 8
==5294== at 0x400C3D: LinkedList::delete_back() (in /home/jon/jball2_lab06/linkedlist)
==5294== by 0x400EEC: main (in /home/jon/jball2_lab06/linkedlist)
这是我使用的测试代码:
for(Item i = 50; i < 100; i++){
ll.insert_back(i);
cout << "Inserted [" << i << "] in back.\n";
}
ll.print();
for(int i = 0; i < 50; i++)
ll.delete_back();
cout << "Removed 50 elements from the back.\n";
ll.print();
当使用 delete_back() 从列表中删除最后一个元素时会发生这种情况
更新 - - - - - - - - - - - - -
问题是如果 end->next 为空,那么 while 循环将永远不会执行,prev_end 永远不会被初始化。已实施修复的发布答案。