0
bool load(const char* dictionary)
{
FILE* infile = fopen(dictionary, "r");
if (infile == NULL)
{
    return false;
    fclose(infile);
}

node* root = malloc(sizeof(node));
node* new_node = root;

if(root == NULL)
{
    return 1;
}

for(int i = 0; i < 27; i++)
{
    root -> children[i] = NULL;
    root -> is_word = false;
}

{
    int count = 0, pos = 0, words = 0;

    for (int c = fgetc(infile); c != EOF; c = fgetc(infile))
    {
        if (c == '\n')
        {
            count++;
        }
        if (isalpha(c) || (c == '\''))
        {

            if (c == '\'')
            {
                pos = 26;
            }
            else
            {
                pos = (c - 'a');
            }

            if (new_node -> children[pos] == NULL)
            {
                new_node -> children[pos] = malloc(sizeof(new_node));
            }
            new_node = new_node -> children[pos];

            if (count > 0)
            {
                new_node -> is_word = true;
                new_node = root;
                words++;
                pos = 0;
                count = 0;
            }
        }
    }
}
free (root);
fclose(infile);
return true;
}

When running code in GDB, I sometimes get a seg fault at "new_node -> is_word = true". It doesn't happen with every word. Some of the words are successfully loaded and is_word is set to true, but it will randomly seg fault when performing this operation with other words in the dictionary. Am I initializing incorrectly? Do I need to set root to NULL somehow when I malloc space for it?

0

You need to initialize every node that you malloc. The easiest way to do this is to use calloc instead (calloc will essentially give you zero'd out memory).

1
  • I haven't used calloc before. Its definition states that I must list not only its size but also the number of elements to allocate. Would a single node be considered 1 element? I tried implementing my code with calloc(1, sizeof(node)), but I still get the seg fault when the code sets is_word = true. – Flesheaters Dec 19 '16 at 3:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .