0

我编写了以下代码。在开头插入、删除、在开头和结尾插入都可以正常工作。粗体标记的内存没有被释放。应该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
-------------------
4

3 回答 3

2

delete不将指针的值设置为 NULL,但指向的内存不再有效(不包含 live node

这意味着cout << temp将打印它仍然拥有的指针的值(并且是 之前的节点地址delete),但是取消引用temp(例如*tempor temp->next)是未定义的行为

注意:在任何地方都没有del修改 指向的指针head,因此您要么不需要双重间接(node**),要么应该将新的头分配给*head.

于 2012-06-18T18:59:45.343 回答
1

正如 Attila 已经指出的那样,在删除指针后取消引用指针是未定义的行为。为了防止意外这样做,最好NULLdelete. 取消引用 NULL 指针会立即导致错误,指出正确的原因。

于 2012-06-18T19:54:07.847 回答
0

在代码中,最好先释放临时节点。然后将 prev->next 赋值为 NULL。这样就很容易理解临时节点不可用,这就是使 prev->next NULL 的方式。

于 2012-06-24T06:55:20.073 回答