在我说大约 500 个条目之后,这个链表代码段错误。
while (item_temp->next != 0) {
在循环内部,它所做的只是转到链表中的下一项。
当我在 gdb 中查看它时,这就是我得到的
(gdb) print item_temp
$1 = (struct item *) 0xc
(gdb) print item_temp->next
Cannot access memory at address 0xc
编辑:
我这样分配它:
struct item* item_temp = malloc(sizeof(struct item));
然后在循环之前我将它设置为等于链表的头部,就像这样
item_temp = table->buckets[code]->head;
只是为了让它知道,在我尝试引用头部之前,我确保头部存在。我就是这样做的。
if (table->buckets[code]->head == 0)
{
table->buckets[code]->head = item_add;
table->occupied_buckets++;
}
这是我的代码示例...如果您需要其他内容,请询问。
struct HT* add(struct HT* table, struct word *wrd, int(*alg)(struct word *wrd))
{
if ((double)table->entries / (double)table->num_buckets > .75)
{
table = resize(table, alg);
}
sort(wrd);
int code = alg(wrd);
code = code % table->num_buckets;
struct item* item_temp = malloc(sizeof(struct item));
struct item* item_add = malloc(sizeof(struct item));
item_add->wrd = wrd;
item_add->next = 0;
if (table->buckets[code]->head == 0)
{
table->buckets[code]->head = item_add;
table->occupied_buckets++;
}
else
{
item_temp = table->buckets[code]->head;
while (item_temp->next != 0) {
item_temp = item_temp->next;
}
item_temp->next = item_add;
}
table->buckets[code]->num_items++;
table->entries++;
if (table->buckets[code]->num_items > table->largest_bucket)
{
table->largest_bucket = table->buckets[code]->num_items;
}
return table;
}