【发布时间】:2016-12-07 23:19:42
【问题描述】:
我正在尝试实现一个链表(我相信这是一个循环链表),但在使用它时,它最终会崩溃。我认为这是因为我使用的遍历指针未正确设置为 0,最终被取消引用并表现出未定义的行为。
感谢您的帮助。
这是我正在使用的功能:
struct records t_head = 0;
struct records* find_id(Rect a)
{
struct records* tmp;
struct records* prev;
// Add first node
if (t_head == NULL) {
tmp = new records;
tmp->b = a;
tmp->id = trecord_count + 1;
tmp->tally.resize(labelsInfo.size());
tmp->frames = 0;
t_head = tmp;
t_head->next = NULL;
trecord_count++;
}
else {
// Check if there is any node that has delete_flag set first
tmp = t_head;
while (tmp) {
if (delete_flag) {
// Delete here
if (tmp == t_head) {
t_head = tmp->next;
delete (tmp);
trecord_count--;
}
else {
prev->next = tmp->next;
delete (tmp);
trecord_count--;
}
}
prev = tmp;
tmp = tmp->next;
}
tmp = new records;
tmp->b = a;
tmp->id = trecord_count + 1;
tmp->tally.resize(labelsInfo.size());
tmp->frames = 0;
tmp->next = t_head;
t_head = tmp;
trecord_count++;
}
return tmp;
}
结构定义为:
struct records {
int id;
Rect b;
vector<int> tally= {};
int frames=0;
int delete_flag=0;
struct records *next;
};
【问题讨论】:
-
你能发布更完整的代码吗?这不是凭空出现的吗?
-
这是标记为 C,但您使用的是
new和delete;你确定你没有使用 C++ 编译器吗? -
您需要向我们提供复制问题所需的最少代码。这意味着我们应该能够编译和运行它,从而复制问题。但是您应该尽可能多地删除代码。 (在准备这个的过程中,你可能会发现自己解决了这个问题。)
-
除非这是一个学习更多关于编码的学术练习,否则这完全是浪费时间。 C++ 标准库有各种各样的容器,包括像链表一样操作的容器。为什么在 C++ 中使用
struct?这应该是class。它应该有一个初始化器来正确填充next之类的东西。它应该有测试。 -
是什么阻止了
prev指向在tmp != t_head时被删除的内存?查看代码,这似乎是可能的,因为您delete tmp然后将您刚刚删除的内容分配给prev。
标签: c++