任何人都可以看到为什么这个程序会产生分段错误

时间:2015-05-12 14:50:01

标签: c 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;
}

2 个答案:

答案 0 :(得分:1)

函数map_insert的签名是

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

如您所见,它旨在返回int。但是你返回node*。通过将问题更改为:

来解决问题
node* map_insert(Map *theMap, char *theKey, void *theItem){

<小时/> 演员:

return (node *)newNode;

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

答案 1 :(得分:1)

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;
}