1

Can someone tell me why I get segmentation fault?

bool load(const char *dictionary)
{

FILE *fp = fopen(dictionary, "r");
if (fp == NULL)
{
    return false;
}

char word[45];


while (fscanf(fp, "%s", word) != EOF)
{
    node *current = root;

    for (int i = 0, n = strlen(word); i < n; i++)
    {
        if (word[i] == '\'')
        {
            if (current -> leaves[26] == NULL)
            {
                node *new_node = malloc(sizeof(node));
                current -> leaves[26] = new_node;
                current = current -> leaves[26];
            }
            else
                current = current -> leaves[26];
        }
        // I get segfault here
        else if (current -> leaves[word[i] - 'a'] == NULL)
        {
            node *new_node = malloc(sizeof(node));
            current -> leaves[word[i] - 'a'] = new_node;

            current = new_node;
        }
        else
            current = current -> leaves[word[i] - 'a'];

    }
    current -> is_word = true;
    counter++;
}

return true;

}

Thanks for any help.

1

Let's take a close look at this line:

(current -> leaves[word[i] - 'a'] == NULL)

If word[i] is a lowercase letter, i.e. it is in the range 97-122, your subtraction will work. However, what happens when word[i] is the latter "A"?

In such a case, you'd have leaves[65 - 97] or leaves[-32]. Obviously, a negative index in an array in C is highly problematic.

You may also find this question and answer helpful.

You must log in to answer this question.

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