谁能看出为什么这个程序会产生分段错误

Can anyone see why this program generates a segmentation fault

我正在编写一个程序来使用单链表实现地图。在编写并包含此插入方法后,程序会生成分段错误,但我不确定这是从哪里来的。

int map_insert(Map *theMap, char *theKey, void *theItem){

   node *newNode = malloc(sizeof(node));

   node *cursor = theMap->root;

   while(cursor->next !=  NULL){
      cursor = cursor->next;
    }

    newNode->key = theKey;
    newNode->item = theItem;
    newNode->next = NULL;


    cursor->next = newNode;

    return (node *)newNode;
}

函数map_insert的签名是

int map_insert(Map *theMap, char *theKey, void *theItem)

如您所见,它旨在 return 和 int。但是你return一个node*。通过将其更改为解决问题:

node* map_insert(Map *theMap, char *theKey, void *theItem){


这里的演员:

return (node *)newNode;

不是必需的,因为 newNode 已经是 node* 类型。

node *cursor = theMap->root;

我假设如果映射为空,root 将为 NULL。

while(cursor->next != NULL)

如果 rootNULLcursor 也是 NULL,并且您在访问 next 字段时取消引用它。

也许将 while 条件更改为:

while (cursor && cursor->next) ?


编辑:这是一个完整的函数:

node * map_insert(Map *theMap, char *theKey, void *theItem){

    node *newNode = malloc(sizeof(node));

    newNode->key = theKey;
    newNode->item = theItem;
    newNode->next = NULL;

    node *cursor = theMap->root;

    if (cursor) {
       while(cursor->next !=  NULL){
          cursor = cursor->next;
        }
        cursor->next = newNode;
    }
    else
    {
        theMap->root = newNode;
    }

    return newNode;
}