0

The relevant snippet of my load function:

FILE* dict = fopen(dictionary, "r");
    bool complete = true;
    for (int c = fgetc(dict); c != EOF; c = fgetc(dict))
    {
        node* head = malloc(sizeof(node));
        if (isalpha(c) && complete)
        {
            c = toupper(c);
            head = root[c - 65];
            complete = false;
        }
        else if (isalpha(c) || c == '\'')
        {
            if (c == '\'')
            {
                head = head->children[26]; 
            }
            else
            {
                c = toupper(c);
                head = head->children[c - 65]; 
            }
            if (head->is_word != true)
            {
                head->is_word = false;
            }  
        }

When I run speller through valgrind and gdb, speller segfaults on the line

if (head->is_word != true)

After playing around with my code I can definitely confirm that accessing the variable is_word in my node pointer causes a segfault regardless of the particular node pointer. That doesn't make any sense to me because (any node pointer x)->is_word seems like a routine operation.

E: struct node and node* head are defined globally.

1 Answer 1

1

To understand the cause of the error, you should understand the semantics of the assignment operator (i.e., =). It simply assigns the value on its right to the variable on its left.

When you did

node *head = malloc(sizeof (node));

and presumably the allocation was successful, a memory address was assigned to head (i.e., head had memory allocated for it that it pointed to).

Here's the thing: if in one of the iterations, the condition

isalpha(c) && complete

is true, head gets root[c - 65] assigned to it. Now, assuming this type-checks, root[c - 65] initially has no memory allocated for it and therefore it could have NULL assigned to it.

And since head is now an alias to root[c - 65], head could also have NULL assigned to it.

If you try to access any member of the struct that head points to at a point where head is NULL, you get a segmentation fault immediately because head does not really point to any structs at this point.

By the way, you could see that easily if you used a tool like gdb.

You must log in to answer this question.

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