0

My implementation of load uses a trie and when I attempt to access the bool is_word I get a segfault. Can you guys help me out? Any suggestions on how to improve my code would be amazing. Thanks everyone!

bool load(const char* dictionary)
{
node* root = malloc(sizeof(node));
for(int i = 0; i < 27; i++) {
    root->children[i] = NULL;
}

node* current = malloc(sizeof(node));
current = root;
for(int i = 0; i < 27; i++) {
    current->children[i] = NULL;
}

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

char letter = 'a';

do {
    letter = fgetc(dict);
    if(letter == EOF) {
        current->is_word = true;
        break;
    }

    if(letter == '\n') {
        current->is_word = true;
        current = root;
    } else {
        int pos = tolower(letter) - 'a';
        if(current->children[pos] == NULL) {
            current->children[pos] = malloc(sizeof(node));
            current->children[pos] = NULL;
        }
        current = current->children[pos];
    }

}while(letter != EOF);

fclose(dict);
return false;

}

2 Answers 2

0

Did you declare and initialize is_word to false?

2
  • I did not. Should that be done in the struct? I tried to set each one to false in the loop, but that didn't work. Jan 4, 2016 at 4:07
  • Define bool is_word when you define your struct. Then you can set it to true if EOF (as you did), or false otherwise.
    – ronga
    Jan 4, 2016 at 7:45
0

I figured it out. I wasn't able to initialize is_word to false because I was setting the whole node to NULL.

You must log in to answer this question.

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