首页 > 解决方案 > 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++;
   }

 }

标签: c

解决方案


在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,NS都是不好的名称。无论如何,您可以做得比 1 个字符名称更好。怎么样dictnode

推荐阅读