c - 链表段错误a

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

最佳答案

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

item_temp = table->buckets[code]->head; 计算结果为 0xc

关于c - 链表段错误a,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15882520/

相关文章:

c - 如何在 C 中的字符串中查找字符串?

c - Eclipse CDT 智能感知

Iphone Objective-c 全局变量不同的值

c - 为什么 GCC 的 __attribute__((__ms_abi__)) 返回值与 MSVC 不同?

c - C中的结构体到数组

c - 从 `setuid` 进程检测父进程死亡

c - 简单的程序占用太多CPU

c - 术语 : what's a pointer?

c - 尝试使用 C qsort 函数时出现问题

c - 使用 clang 从命令行链接 .dylib 库