【发布时间】:2015-07-23 12:50:48
【问题描述】:
我正在编写一个程序来使用单链表实现地图。在编写并包含此插入方法后,程序会生成分段错误,但我不确定这是从哪里来的。
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返回的指针(这可能是segfault的原因):你确定
theMap被正确传递(即:它是一个有效的指针),并且是theMap->root有效(如果是NULL,cursor->next取消引用 NULL 指针)并检查malloc的返回值,它可以返回NULL。无论哪种方式,使用-g标志 (gcc) 编译,并逐步执行代码 (gdb)
标签: c segmentation-fault