c - searchAndRemove C 中链表的元素

标签 c pointers search linked-list

我正在用 C 编写一个过程,在链接列表中查找一个元素,将其保存在动态分配的其他元素中,释放它,然后返回“保存的”元素。但是我想从程序返回的元素不正确,当我注释 free() 行时,它就像一个魅力。我认为如果我为一个元素分配内存然后为其分配一些值,它将仍然是一个单独的实例,而不是仍然依赖于旧值

typedef struct Queue {
    char name[2];
    int time;
    int priority;
    struct Queue* next;
}Queue;

Queue *searchAndRemove (Queue *x, char *name)
{
    Queue *buf = malloc(sizeof(Queue));
    Queue *it = x;

    while (it->next != NULL) {
        if (it->next->name[0] == name[0] && it->next->name[1] == name[1]) {
            buf = it->next;
    //      Queue *del = it->next;
            it->next = it->next->next;
    //      free(del);
        }
        it = it->next;
    }
    buf->next = NULL;   

    return buf;
}

最佳答案

假设您的链接列表为

1 -> 2 -> NULL

其中 12 表示节点,箭头指向列表中的下一个节点。

假设您正在搜索的节点是列表中的最后一个节点。即,2

在某个时刻,it 指向 1 且条件 it->next->name[0] == name[0] && it-> next->name[1] == name[1] 变为 true。

buf = it->next;2 存储在 buf 中。 it->next = it->next->next; 使 it->next 的值为 NULL

然后 while 循环的最后一个语句 it = it->next; 使 it 的值为 NULL.

在下一次迭代中,当 it 时,测试条件 it->next != NULL 计算 it->next
即,尝试取消引用NULL 指针。这会调用未定义的行为。

这可能是你的问题。

一旦找到匹配项,您可以通过中断循环来避免这种情况,例如

if (it->next->name[0] == name[0] && it->next->name[1] == name[1]) {
     buf = it->next;
     it->next = it->next->next;
     break;
}

此外,您还应该确保 searchAndRemove() 开头的 x 不是 NULL

请注意,如果取消注释这两行,则会释放 delbuf 指向的内存,因为它们都指向相同的内存位置。如果您在释放 del 后返回 buf,则您使用的是未分配的内存,因此会调用未定义的行为。

关于c - searchAndRemove C 中链表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222469/

相关文章:

c++ - c_str使用不当

PHP SQL 如何在使用 CASE 和表 JOIN 时获取总行数

c - 从具有可预测格式的字符串中提取两个子字符串

c - 使用 fscanf 从文件中读取一个整数

c - 二叉搜索树索引

c - 如何正确关闭管道

c - 为什么malloc返回一个指针?

c++ - 带指针的基本整数交换

search - Sitecore 索引搜索

java - 如何以循环方式突出显示 TextArea 中的单词