简体   繁体   English

链表分割故障a

[英]linked list segmentation fault a

After I'd say about 500 entries, this linked list code seg faults. 在我说了大约500个条目之后,此链接列表代码出现了段错误。

while (item_temp->next != 0) {

Inside the loop, all it does is goes to the next item in the linked list. 在循环内部,它所做的只是转到链接列表中的下一项。

When I look at it in gdb, here's what I get 当我在gdb中查看它时,这就是我得到的

(gdb) print item_temp
$1 = (struct item *) 0xc
(gdb) print item_temp->next
Cannot access memory at address 0xc

EDIT: 编辑:

I allocate it like so: 我这样分配它:

struct item* item_temp = malloc(sizeof(struct item));

and then right before the loop I set it equal to the head of the linked list like so 然后在循环之前,我将其设置为等于链表的开头,如下所示

    item_temp = table->buckets[code]->head;

And just for sake of making it known, before I try to reference the head, I make sure the head exists. 只是为了让人们知道它,在我尝试引用头部之前,请确保头部存在。 I do that like so. 我就是这样

if (table->buckets[code]->head == 0)
{
    table->buckets[code]->head = item_add;
    table->occupied_buckets++;
}

Here's a sample of my code... if you need something else, please ask. 这是我的代码示例...如果您还需要其他内容,请询问。

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;
   }

From your question, it is clear that item_temp is pointing to location 0xc and de-referencing next is causing the code to access an invalid address and hence, the segmentation fault. 从您的问题来看,很明显item_temp指向位置0xcnext取消引用导致代码访问无效地址,从而导致分段错误。

item_temp = table->buckets[code]->head; is evaluating to 0xc . 正在评估为0xc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM