Inserting word from a text file into a tree in C

2019-07-01 09:07发布

问题:

I have been encountering a weird problem for the past 2 days and I can't get to solve it yet. I am trying to get words from 2 texts files and add those words to a tree. The methods I choose to get the words are refereed here: Splitting a text file into words in C.

The function that I use to insert words into a tree is the following:

void InsertWord(typosWords Words, char * w)
{
   int error ;
   DataType x ;
   x.word = w ;
   printf(" Trying to insert word : %s \n",x.word );
   Tree_Insert(&(Words->WordsRoot),x, &error) ;
   if (error)
   {
       printf("Error Occured \n");
   }
}

As mentioned in the link posted , when I am trying to import the words from a text file into the tree , I am getting "Error Occured". For once again the function:


the text file :

a

aaah

aaahh


char this_word[15];
while (fscanf(wordlist, "%14s", this_word) == 1) 
{
   printf("Latest word that was read: '%s'\n", this_word);
   InsertWord(W,this_word);
}

But when I am inserting the exact same words with the following way , it works just fine.

    for (i = 0 ; i <=2 ; i++)
    {
    if (i==0)
        InsertWord(W,"a");
    if (i==1)
        InsertWord(W,"aaah");
    if (i==2)
        InsertWord(W,"aaahh");
    }

That proves the tree's functions works fine , but I can't understand what's happening then.I am debugging for straight 2 days and still can't figure it. Any ideas ?

回答1:

When you read the words using

char this_word[15];
while (fscanf(wordlist, "%14s", this_word) == 1) 
{
   printf("Latest word that was read: '%s'\n", this_word);
   InsertWord(W,this_word);
}

you are always reusing the same memory buffer for the strings. This means when you do

x.word = w ;

you are ALWAYS storing the SAME address. And every read redefine ALL already stored words, basically corrupting the data structure.

Try changing the char this_word[15]; to char *this_word; and placing a this_word = malloc(15);in the beggining of thewhile` loop instead, making it allocate a new buffer for each iteration. So looking like

char *this_word;
while (fscanf(wordlist, "%14s", this_word) == 1) 
{
   this_word = malloc(15);
   printf("Latest word that was read: '%s'\n", this_word);
   InsertWord(W,this_word);
}

As suggested by Michael Walz a strdup(3) also solves the immediate problem.

Of course you will also have do free up the .word elements when finished with the tree.



回答2:

Seems like the problem was in the assignment of the strings.Strdup seemed to solve the problem !