簡體   English   中英

在 c 中使用 realloc 4 次后訪問結構成員的段錯誤

[英]Segfault accessing struct member after using realloc 4 times in c

每當 nTable->size = 4 時,我都會遇到段錯誤,而且我一生都無法弄清楚為什么。 我在發生段錯誤的代碼中添加了注釋。 目的是讀取一個文本文件並創建一個已讀單詞的 trie(我認為這是一個 trie?),如果它們共享相同的前幾個字母,則重新使用先前單詞的字母。 此代碼僅使用 1 個單詞 (abcde) 進行演示

#include <stdbool.h>//for bool
#include <stdlib.h> //for malloc
#include <string.h> //strlen, strchr
#include <ctype.h>  //tolower
#include <stdio.h>

#define CHARACTERS 27

typedef struct node
{
    struct node *nLetter[CHARACTERS];
    bool end;
    int size;
} node;

const char *cLetters = "abcdefghijklmnopqrstuvwxyz'";

node *nTable;

int main ()
{
    char *cWord = "abcde";

    nTable = malloc(sizeof(node));

    if (nTable == NULL){
        return false;
    }

    nTable->size = 1;   //initialize table to size 1
    nTable->end = false;//word not 0 letters

    node *nPath = NULL; //create the path between each letter of the word

    int iLen = 0;

    iLen = strlen(cWord);

    if(cWord[iLen - 1] == '\n') //strlen counts \n as a character, but not \0 (end of string). -1 if \n included
    {
        iLen--;
    }

//store word in table

    nPath = nTable; //reset path to beginning of table

    for (int n = 0; n < iLen; n++)
    {
        char *p = strchr(cLetters, tolower(cWord[n]));

        //Check Path
        if (nPath->nLetter[p - cLetters] == NULL)   //If path exists, move along path (in else below)
        {                                   //if no path yet, create below.
            nTable = realloc(nTable, ++nTable->size  * sizeof(node));    //increase size of nTable by 1 node
            if (nTable == NULL)
            {
                return false;   //failed to increase size of nTable
            }

            //Connect Path
            nPath->nLetter[p - cLetters] = nTable + (nTable->size - 1) * sizeof(node);    //create path from previous letter to next
            nPath = nPath->nLetter[p - cLetters];         //update nPath pointee to newest letter

            if (n + 1 == iLen)  //last letter of word
            {
                nPath->end = true;
            }
            else    //not last letter of word
            {
                nPath->end = false;   //SEGFAULT HERE when nTable->size is 4 or more
            }
        } //end if new path (if)
        else    //path exists, move along path
        {
            nPath = nPath->nLetter[p - cLetters];
        }
    }
    return true;
}

我認為有問題的行是這一行:

nPath->nLetter[p - cLetters] = nTable + (nTable->size - 1) * sizeof(node);    //create path from previous letter to next

當你做指針運算時,你不應該乘以類型的大小。 相反,該行應該是:

nPath->nLetter[p - cLetters] = nTable + nTable->size - 1;

暫無
暫無

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

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