簡體   English   中英

運行C程序時出現分段錯誤

[英]Segmentation fault when run C program

我剛收到一條錯誤消息,說我的程序中存在分段錯誤。 我使用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函數中HashTable *curr_table = h[strlen(data)]; h[strlen(data)]可以為NULL ,這就是為什么curr_table (您最終將其作為h傳遞給exist函數)為NULL

致電

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM