c++ - 删除链表的最后一个节点后内存未释放

标签 c++ pointers data-structures linked-list delete-operator

我编写了以下代码。在开头插入、删除、在开头和结尾插入都可以正常工作。粗体标记的内存未被释放。应<强>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 (例如 *temptemp->next )是未定义的行为

注意:del 中不存在你修改了head指向的指针吗? ,所以您要么不需要双重间接寻址( node** ),要么您应该将新头分配给 *head .

关于c++ - 删除链表的最后一个节点后内存未释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11089233/

相关文章:

c++ - 具有模板参数的模板类上的赋值运算符重载

c - 为什么我不能用字符串初始化这个指针?

java - 如何使用节点在堆数据结构中实现渗透功能?

c++ - 检测继承类并将其转换为基类

c++ - 如何使用直接io写入小文件而不扩展文件大小

delphi - 从指针问题中访问值

data-structures - 链表删除的时间复杂度

javascript - 如何通过索引数组重新排列数组?

c++ - 将 char num[50] 复制到 std::string

C编程: dereferencing pointers