我运行这段代码,无论我使用什么输入,我每次都会在第 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;
}
最佳答案
我通过以下更改重写了您的函数:
- 设置
n->next
,之前没有。 - 重写 if-else 以在 block 外使用通用代码。
- 如果节点已存在于散列中,则修复内存泄漏。
- 删除了不正确的
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/