c - 我在第 19 次运行 addNode 函数时遇到了 SegFault,但我不知道为什么

标签 c segmentation-fault

我运行这段代码,无论我使用什么输入,我每次都会在第 19 次通过 addNode 函数遇到段错误。我是 c 的新手,我的智慧就在这里结束了。有人有主意吗?我只是在寻找它可能发生的一般原因,而不是针对我的情况的任何具体原因。这毕竟是一项学校作业,我不想违反任何学术诚信规则。

int addNode(size_t t, Node** ht){
    Node* n = (Node*)malloc(sizeof(Node));
    int hashVal = hash(t);
    n->value = t;
    if (ht[hashVal] == NULL){
        ht[hashVal] = n;
        return 1;
    }
    else{
        Node* nptr = ht[hashVal];
        while (nptr != NULL){
            if (nptr->value == t){
                return 0;
            }
            nptr = nptr->next;
        }
        nptr->next = n;
    }
    ht[hashVal] = n;
    return 1;
}

最佳答案

我通过以下更改重写了您的函数:

  1. 设置n->next,之前没有。
  2. 重写 if-else 以在 block 外使用通用代码。
  3. 如果节点已存在于散列中,则修复内存泄漏。
  4. 删除了不正确的 nptr->next = n; 行。如果你想添加到尾部,你可以做这样的事情,但你差了一个。
int addNode(size_t t, Node** ht)
{
    Node* n = (Node*)malloc(sizeof(Node));
    int hashVal = hash(t);
    n->value = t;
    if (ht[hashVal] != NULL) {  // <-- Rewrote if, removed else
        Node* nptr = ht[hashVal];
        while (nptr != NULL){
            if (nptr->value == t) {
                free(n);  // <-- Memory leak if you don't do this
                return 0;
            }
            nptr = nptr->next;
        }
    }
    n->next = ht[hashVal]; // <-- This was missing
    ht[hashVal] = n;
    return 1;
}

关于c - 我在第 19 次运行 addNode 函数时遇到了 SegFault,但我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28774152/

相关文章:

c - 动态内存分配 - 时间和原因

soap - 使用soap的段错误php7 symfony cli命令

c - 我的 while 循环出现段错误

c - 矩阵优化 - 使用内在函数和循环展开时出现段错误

c - C语言中char arr[] = "OX|-"如何工作

c - 删除链表头后出现垃圾打印

c - 如何将数组拆分为特定大小

c - 如何在字符串中存储零

c++ - C++ 递归函数中的段错误

c - 读取文件时出现段错误