gpt4 book ai didi

c - 运行C程序时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:24 25 4
gpt4 key购买 nike

我刚收到一条错误消息,说我的程序中存在段错误。我使用 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

最佳答案

那一行是错误。 GDB在告诉你

0x0000000000400baa in exist (h=0x0, data=0x644660 "a\n") at G1.c:129

h 是一个NULL 指针(指向地址 0)。当您使用 h->nodes[index] 取消引用它时,您最终会出现段错误。当您设置 HashTable *curr_table = h[strlen(data)]; 时,问题可能出在您的 add_to_hash 函数中。 h[strlen(data)] 可能是 NULL,这就是为什么 curr_table(您最终将其传递为 h您的 exist 函数)是 NULL

关于c - 运行C程序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38340354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com