0

I think there might be something wrong with the fscanf use because when using gbd temp's value never changes, it stays as NULL. Also, word's value stays as 0 throughout the entire program and every word in the text file appears as misspelled. Can someone help me find the error?

 bool load(const char* dictionary)
{

    root = newnode();

    //open dictionary file
    FILE* dict = fopen(dictionary, "r");
    if (dict == NULL)
    {
        printf("Could not open dictionary\n");
        return false;
    }

    //retrieve words from dictionary
    char* temp = NULL;

    while (fscanf(dict, "%s", temp) == 1)
    {
        insert(root, temp);
        words++;
    }

    return true;
}

NOTE: root and words variables are global variables.

Relevant code:

#define ALEN 27

//global variables 
node* root;
int words;

//trie nodes' definition.
typedef struct trie
{
    bool is_word;
    struct trie* children[ALEN];
} node;

    //create a node
node* newnode(void)
{
    node* new_node = malloc(sizeof(node));
    new_node->is_word = false;
    for (int i = 0; i < ALEN; i++)
    {
        new_node->children[i] = NULL;
    }
    return new_node;
}

//insert word into trie
void insert(node* root, char* temp)
{
    int len = strlen(temp);
    node* trav = root;

    for (int i = 0; i < len; i++)
    {
        if (trav->children[temp[i] - 'a'] == NULL)
        {
            trav->children[temp[i] - 'a'] = newnode();
        }

        trav = trav->children[temp[i] - 'a'];
    }
    trav->is_word = true;
}
2
  • Can't tell a thing from this limited code. Please edit and add the code for newnode and insert functions, along with any other related code. Also include the declarations for root and the structure type. – Cliff B Nov 5 '16 at 0:33
  • Edited, please take a look. Thanks! – Carlos C Nov 5 '16 at 0:42
1

I'm highly suspicious of the following two lines:

char* temp = NULL;
while (fscanf(dict, "%s", temp) == 1)

The temp var is a pointer set to NULL, which you then try to read a string into. No memory space has been allocated to it, so what happens? Perhaps you should try declaring it as an array of a fixed size instead.

There may be other issues, but this is a starting point.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thanks a lot! I was able to fix the bug by changing temp to a fixed size array (temp[LENGTH]). Now the words load and misspelled word list is correct. – Carlos C Nov 5 '16 at 1:19

You must log in to answer this question.

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