【问题标题】:segmentation fault by malloc [duplicate]malloc的分段错误[重复]
【发布时间】:2014-08-03 02:55:18
【问题描述】:

我的程序中存在严重的分段错误问题。

代码:

bool load(const char* dictionary)
{
    // creating a trie data structure
    typedef struct trie
    {
        bool is_word;        
        struct trie* alphabets[27];
    }trie;
    trie* root = NULL;

    //opening the dictionary file
    FILE* infile = fopen(dictionary, "r");
    if (infile == NULL)
    {
        return false;
    }
    char s[45];
    int i = 0, n = sizeof(trie);
    bool start = true;
    trie* tmp = NULL;
    for (int c = fgetc(infile); c != EOF; c = fgetc(infile))
    {
        c = tolower(c);
        if (isalpha(c) || c == '\'')
        {   
            s[i] = c;
            i++;
            start = false;
        }
        else if (start == false)
        {
            for (int j = 0; j < strlen(s); j++)
            {
                int c_int = (int) (s[j] - 'a');
                if (tmp == NULL || root->alphabets[c_int] == NULL)
                {
                    root->alphabets[c_int] = malloc(n);
                    tmp = root->alphabets[c_int];
                }
                else if (tmp != NULL)
                {
                    tmp->alphabets[c_int] = malloc(n);
                    tmp = tmp->alphabets[c_int];
                }
                else if (root->alphabets[c_int] != NULL)
                {
                    tmp = root->alphabets[c_int];
                }
                if (j == strlen(s) - 1)
                {
                    tmp->is_word = true;
                }
            }
        }
    }
    return true;

root-&gt;alphabets[c_int] = malloc(n); 是给出段错误的行

【问题讨论】:

标签: c segmentation-fault


【解决方案1】:

你需要为root分配内存。

即:

root = malloc(sizeof(trie));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 2014-03-29
    • 2015-01-29
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    相关资源
    最近更新 更多