【问题标题】:How to fix a segmentation fault error while accessing this next in linked list?如何在链表中访问下一个时修复分段错误错误?
【发布时间】:2019-05-10 03:55:45
【问题描述】:

我是一名学习数据结构的学生,试图实现一个 hashmap 函数,该函数将使用链表的节点添加元素。当我调用下一个值时,我最终在我的 else 语句中得到一个段错误,我不知道为什么。任何帮助表示赞赏,谢谢大家。

  void insertMap (struct hashMap * ht, KeyType k, ValueType v)
  {  /*write this*/
int idx = stringHash1(k);
struct hashLink * hlnk;
struct hashLink * plink;
assert(ht);

if(ht->table[idx] == NULL){
    hlnk = (struct hashLink *) malloc(sizeof(struct hashLink));
    hlnk->value = v;
    hlnk->key = k;
    hlnk->next = NULL;
    ht->table[idx] = hlnk;
    ht->count++;
}

else{
            plink = ht->table[idx];
            hlnk = (struct hashLink *) malloc(sizeof(struct hashLink));
            hlnk->value = v;
            hlnk->key = k;
            hlnk->next = plink->next;
            plink->next = hlnk;
            ht->count++;
    }
}

【问题讨论】:

  • 放置整个代码总是有帮助的,或者如果不是数据结构和函数的相关定义。我们不知道你使用的 struct hashMap、struct hashLink 和类似的其他函数的定义。代码中的错误可能在任何地方。
  • 检查您最初是否真的将事物设置为 NULL。如果您没有将所有可能的 ht->table[idx]entries 设置为 NULL,那么当您真的想进入 if 语句的第一部分时,您可能最终会进入 else 部分。

标签: c linked-list hashmap


【解决方案1】:

如果您尝试将节点插入到列表的前面,您还需要更新 ht->table[idx]

目前您正在更新您的 else 案例中的本地指针 plink

else{
           .....
            plink->next = hlnk; //this line only updates the local pointer
            ht->count++;
    }

应该是

  else{
               .....
               ht->table[idx] = hlnk;
  }

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    相关资源
    最近更新 更多