你能说说,为什么执行下一段代码会导致错误:
void del (num*&head) {
num*temp = 0;
if (head!=0) {
temp = head;
delete temp;
del (head->next);
}
else return;
}
错误:
Access violation reading location 0xcdcdcdc1.
而下一个代码可以正常工作:
void del (num*&head) {
if (head!=0) {
del (head->next);
delete head;
}
else return;
}
最佳答案
删除 temp
会使 head
无效,因为它们都指向同一个对象。 head->next
尝试访问已删除的对象,给出未定义的行为。您应该改为存储 head->next
,这样您就不必访问已删除的对象:
if (head) {
num * temp = head->next;
delete head;
del (temp);
}
您正在运行调试版本,因此删除的内存被设置为垃圾,而不是保留其旧内容。这意味着尝试使用从中读取的值作为指针将很快触发访问冲突,帮助您找到问题的根源。
第二个版本会等到您处理完对象后再删除它,因此没有未定义的行为。
但是,递归不是一个好主意,因为如果列表太长,它可能会导致堆栈溢出。迭代会更安全:
while (head) {
num * temp = head->next;
delete head;
head = temp;
}
关于c++ - 递归删除链表c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28724360/