簡體   English   中英

strncpy中的SEGMENTATION FAULT-從字典加載

[英]SEGMENTATION FAULT in strncpy - load from dictionary

我有此功能“加載”,在這里我從字典中讀取單詞,然后將它們放在鏈接列表的哈希表中。 當我嘗試讀取一行並將其保存在new_node-> text中時,編譯器將返回SEGMENTATION FAULT,但我不知道為什么。 使用strncpy時出現錯誤信息。

#define HASHTABLE_SIZE 76801


typedef struct node
{
        char text[LENGTH+1];
        //char* text;
        //link to the next word
        struct node* next_word;
}
node;


    node* hashtable[HASHTABLE_SIZE];

    bool load(const char* dictionary)
    {
        FILE* file = fopen(dictionary,"r");
        unsigned long index = 0;
        char str[LENGTH+1];

        if(file == NULL)
        {
            printf("Error opening file!");
            return false;
        }

        while(! feof(file))
        {
            node * new_node = malloc(sizeof(node)+1000);


            while( fscanf(file,"%s",str) > 0)
            {
                printf("The word is %s",str);
                strncpy(new_node->text,str,LENGTH+1);
                //strcpy(new_node->text,str);

                new_node->next_word = NULL;
                index = hash( (unsigned char*)new_node->text);

                if(hashtable[index] == NULL)
                {
                    hashtable[index] = new_node;
                }
                else
                {
                    new_node->next_word =  hashtable[index];
                    hashtable[index] = new_node;
                }

                n_words++;

            }
            //free(new_node);



        }
        fclose(file);
        loaded = true;

        return true;    
    }

讓我們逐行查看您的代碼,好嗎?

    while(! feof(file))
    {

這不是使用feof的正確方法-查看文章為什么“ while(!feof(file))”總是錯誤的? 就在StackOverflow上。

        node * new_node = malloc(sizeof(node)+1000);

嗯。。好。 我們為一個節點和1000個字節分配空間。 有點奇怪,但是嘿... RAM很便宜。

        while( fscanf(file,"%s",str) > 0)
        {

嗯... 另一個循環? 好...

            printf("The word is %s",str);
            strncpy(new_node->text,str,LENGTH+1);
            //strcpy(new_node->text,str);

            new_node->next_word = NULL;
            index = hash( (unsigned char*)new_node->text);

嘿! 等一下...在第二個循環中,我們不斷重復覆蓋new_node ...

            if(hashtable[index] == NULL)
            {
                hashtable[index] = new_node;
            }
            else
            {
                new_node->next_word =  hashtable[index];
                hashtable[index] = new_node;
            }

假設兩個詞都散列到同一個存儲桶中,一秒鍾:

好的,因此第一次通過循環, hashtable[index]將指向NULL並設置為指向new_node

通過循環第二次, hashtable[index]不為NULL因此new_node指向任何hashtable[index]指向(hint: new_node ),並且將hashtable[index]指向new_node

你知道什么是我們的鴨嘴龍嗎?

現在假設它們沒有散列到同一存儲桶:

現在,其中一個存儲桶包含錯誤的信息。 如果您先在存儲區1中添加“ hello”,然后在存儲區2中首先添加“再見”,則當您嘗試遍歷存儲區1時,您可能會(僅由於鏈接代碼已損壞)在以下位置找到不屬於存儲區1的“再見”所有。

您應該為要添加的每個單詞分配一個節點。 不要重復使用同一節點。

暫無
暫無

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

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