我刚收到一条错误消息,说我的程序中存在分段错误。我使用gdb
跟踪它,下面是我发现它的地方。我该如何解决?
void add_to_hash(HashTable **h, char *data)
{
int index = hash_value(data);
HashTable *curr_table = h[strlen(data)];
Node * exist_node = exist(curr_table, data);
if (exist_node == NULL)
{
Node *new_node = (Node*)malloc(sizeof(Node));
if (new_node == NULL) {
printf("Error allocating memory for new bucket\n");
exit(1);
}
if (data != NULL)
{
new_node->data = strdup(data);
new_node->next = curr_table->nodes[index];
curr_table->nodes[index] = new_node;
free(data);
}
}
else {
return;
}
}
//Rerturn the exist data.
Node* exist(HashTable* h, char* data)
{
int index = hash_value(data);
Node* list = NULL;
list = h->nodes[index];//gdb told me this line has error.
if (list) {
for (; list != NULL; list = list->next) {
if (strcmp(data, list->data) == 0) {
return list;
}
}
}
return NULL;
}
这是我从gdb
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400baa in exist (h=0x0, data=0x644660 "a\n") at G1.c:129
129 list = h->nodes[index];
(gdb) bt
#0 0x0000000000400baa in exist (h=0x0, data=0x644660 "a\n") at G1.c:129
#1 0x0000000000400afa in add_to_hash (h=0x603250, data=0x644660 "a\n") at G1.c:105
#2 0x0000000000400920 in main (argc=3, argv=0x7fffffffebf8) at G1.c:55
答案 0 :(得分:1)
该行是错误。 GDB告诉你
0x0000000000400baa in exist (h=0x0, data=0x644660 "a\n") at G1.c:129
h
是NULL
指针(指向地址0)。当您使用h->nodes[index]
取消引用它时,您最终会发生segfaulting。设置add_to_hash
时,问题可能出在HashTable *curr_table = h[strlen(data)];
功能中。 h[strlen(data)]
可以是NULL
,这就是curr_table
(您最终将h
传递给exist
函数)的原因NULL
。
答案 1 :(得分:1)
致电
HashTable *curr_table = h[strlen(data)];
返回NULL。我们知道这一点,因为gdb
报告传递给exist
函数的参数值:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400baa in exist (h=0x0, data=0x644660 "a\n") at G1.c:129
^^^^^^
129 list = h->nodes[index];