0

I am having a serious problem of segmentation fault in my program.

Code:

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->alphabets[c_int] = malloc(n); is the line giving a seg fault

halfer
  • 19,824
  • 17
  • 99
  • 186
Rajat Vijay
  • 102
  • 1
  • 9
  • The sample file to read from would give you more probability of response. Try to give all the information needed to reproduce the problem, begin with a [minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). – NetVipeC Aug 03 '14 at 03:25

1 Answers1

3

You need to allocate memory for root.

That is:

root = malloc(sizeof(trie));
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Ed Heal
  • 59,252
  • 17
  • 87
  • 127