链表分段错误

时间:2013-04-08 15:02:55

标签: c

在我说了大约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;
   }

1 个答案:

答案 0 :(得分:1)

从您的问题来看,很明显item_temp指向位置0xc,并且取消引用next会导致代码访问无效地址,从而导致分段错误。

item_temp = table->buckets[code]->head;正在评估0xc