【问题标题】:Deleting linked list in c- crash在 c-crash 中删除链表
【发布时间】:2016-04-13 16:33:28
【问题描述】:

我正在尝试删除 PItem 列表。这是PItem的声明

typedef struct Item{
    int num;
    float price;
    struct Item* next;
}*PItem;

这是我尝试删除列表的功能

void deleteList(PItem* ptr, PItem *tail){
    PItem *temp;
    while ((*ptr)->next){
        temp = ptr;
        *ptr = (*ptr)->next;
        free(*temp);
    }
    tail = NULL;
}

奇怪的是它只在循环的第二次运行时崩溃,在

free(*temp);

有谁知道问题出在哪里?

提前致谢。

【问题讨论】:

  • 在调试模式下你保证磁头不会丢失它的参考吗?它会给你任何错误吗?如果是,发布它/他们。或者它会立即对你产生影响?
  • 立即崩溃 - 没有错误
  • 编程时我从来没有遇到过这种情况。我不知道任何会立即使 VS 崩溃的错误您是否尝试检查日志以进行故障排除?
  • 不...它不会使实际的 VS 崩溃,它会使 c 程序崩溃

标签: c list linked-list crash


【解决方案1】:

问题是您使用的间接性超出了您的需要。 temp 变量应该是一个指针,而不是指向指针的指针。执行此操作时会发生以下情况:

// Temp points to the same pointer as ptr, so
temp = ptr;
// when the value pointed to by ptr changes, so does the value pointed to by temp
*ptr = (*ptr)->next;
// When you free *temp, you also free *ptr
free(*temp);

解决这个问题很简单:将temp 声明为PItem,并使用它来复制ptr

PItem temp;
while (*ptr) { // Loop should proceed till *ptr is NULL, not (*ptr)->next
    temp = *ptr; // Copy the pointer's value
    *ptr = temp->next; // Advance *ptr
    free(temp); // Delete temp, which points to the old *ptr
}
// tail is a pointer to a pointer, so you should add * to the assignment
*tail = NULL;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 2018-10-14
    • 2022-07-26
    • 2017-02-20
    • 2018-08-30
    • 2015-01-30
    • 2019-05-10
    • 2021-07-25
    相关资源
    最近更新 更多