- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在用 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
其中 1
和 2
表示节点,箭头指向列表中的下一个节点。
假设您正在搜索的节点是列表中的最后一个节点。即,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
。
请注意,如果取消注释这两行,则会释放 del
和 buf
指向的内存,因为它们都指向相同的内存位置。如果您在释放 del
后返回 buf
,则您使用的是未分配的内存,因此会调用未定义的行为。
关于c - searchAndRemove C 中链表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222469/
我正在用 C 编写一个过程,在链接列表中查找一个元素,将其保存在动态分配的其他元素中,释放它,然后返回“保存的”元素。但是我想从程序返回的元素不正确,当我注释 free() 行时,它就像一个魅力。我认
我是一名优秀的程序员,十分优秀!