我编写了以下代码。在开头插入、删除、在开头和结尾插入都可以正常工作。粗体标记的内存未被释放。应<强>cout<<temp
报错?请评论此代码的正确性。
void del(node** head)
{
node* temp = (*head)->next;
node* prev = *head;
while(temp ->next!= NULL)
{
prev = temp;
temp = temp -> next;
}
cout<<endl<<temp;
cout<<endl<<prev;
//delete prev ->next;
prev -> next = 0;
delete temp;
cout<<endl<<"temp after free"<<temp;
cout<<endl<<prev;
}
void main()
{
node* head = NULL;
int x = 5;
head = insert(head,x);
insert(head,6);
insert(head,7);
insert(head,8);
print(head);
del(&head);
print(head);
getch(); }
输出:
Empty List
|5| at 00673BF0
-------------------
|6| at 00673C30
-------------------
|7| at 00673FB8
-------------------
|8| at 00673FF8
-------------------
00673FF8
00673FB8
temp after free00673FF8
00673FB8
|5| at 00673BF0
-------------------
|6| at 00673C30
-------------------
|7| at 00673FB8
-------------------
最佳答案
delete
没有将指针的值设置为 NULL,但是指向的内存不再有效(不包含活的 node
)
这意味着cout << temp
将打印它仍然具有的指针的值(并且是 delete
之前的节点地址),但取消引用 temp
(例如 *temp
或 temp->next
)是未定义的行为
注意:del
中不存在你修改了head
指向的指针吗? ,所以您要么不需要双重间接寻址( node**
),要么您应该将新头分配给 *head
.
关于c++ - 删除链表的最后一个节点后内存未释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11089233/