c - C语言错误;分段错误与方法
问题描述
所以我对这段代码有一个分段错误,我不知道为什么。我认为这与我使用 NULL 错误(?)的事实有关,但我不认为就是这样。.我尝试添加更多错误消息,看看我是否可以去任何地方,但我仍然得到同样的错误/:
char* lookup(Dictionary D, char* k){
Node N = D->head;
if(D == NULL){
fprintf(stderr, "Error: calling lookup() on null Dictionary");
exit(EXIT_FAILURE);
}
while(N!=NULL){
if(strcmp(N->key,k)==0){
return N->value;
break;
}
N = N->next;
}
return NULL;
}
void insert(Dictionary D, char* k, char* v){
// Node N = D->head;
if(D==NULL){
fprintf(stderr, "Error: inserting on a null Dictionary\n");
exit(EXIT_FAILURE);
}
if(lookup(D,k)!=NULL){
fprintf(stderr, "already existing\n");
exit(EXIT_FAILURE);
}
else{
if(D->numItems==0){
Node N;
N = newNode(k,v);
D->head = N;
D->numItems++;
}
//if there is only a head node, add node after it
else{
Node S = D->head;
while(S!=NULL) {
S = S->next;
}
S->next = newNode(k,v);
}
D->numItems++;
}
}
解决方案
在lookup() 函数中
Node N = D->head;
if(D == NULL){
在检查它是否为 NULL 之前,您已经访问了 D。这可能导致 NULL 指针访问和核心转储。
在 insert() 函数中:
while(S!=NULL) {
S = S->next;
}
// You are guaranteed that S is now == NULL, so the
// next line is a NULL pointer access.
S->next = newNode(k,v);
你需要保留最后一项,这样你就可以说last->next = newNode(k, v);
另外:如果集合中有 0 个项目,不会numItems
增加两次吗?由于代码格式错误,很难说...
附加评论:
- 您显然拥有 Dictionary 和 Node 的 typedef,它们隐藏了它们是指针的事实。不要那样做。这会让任何阅读代码的人感到困惑。
- 一个非常常见的约定是类型以大写字母开头,但不以变量开头,因此
D
,N
和S
都是不好的名称。无论如何,您可以做得比 1 个字符名称更好。怎么样dict
和node
推荐阅读
- javascript - 在 react js 中启用按钮后如何聚焦?
- nodes - 运行 kubectl interfaceservices 命令时超出上下文截止日期
- c - 编译器不接受有效代码?错误 C2447:“{”:缺少函数头(旧式正式列表?)
- python - Python Pandas Datetime过滤每个月N个工作日之前的行
- react-native - Cookie 未正确存储在 ios 模拟器中
- html - 如何使用侧边栏将引导导航栏修复到顶部
- cookies - 经典 ASP 在 cookie 上使用“SameSite”
- mysql - 不满足条件时如何从子查询中返回零而不是 null
- powershell - Powershell字典排序和迭代
- javascript - 打印预览关闭后未触发 OnPrintDialogClose 方法