Reputation: 147
I hope i don't get voted down to quickly for this, but I have a project I'm working on for school in which I have to build a spell checker. I decided to use a trie, and it seems to be working, but I have a bug I can't find. I think the issue is in the following,
bool load(const char* dictionary)
{
if (!rootNode)
{
rootNode = trieNodeCreate();
if (!rootNode)
{
printf("could not allocate root node");
return false;
}
}
// Open the file
FILE* fp = fopen(dictionary, "r");
if (fp == NULL)
{
printf("could not open dictioanry %s\n", dictionary);
return false;
}
int index = 0;
for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
{
char word[LENGTH];
if (c != '\n' )
{
word[index] = c;
index++;
}
else
{
trieWordInsert(word, rootNode);
index = 0;
wordCount ++;
}
}
fclose(fp);
if (wordCount)
{
return true;
}
return false;
}
but I've been unable to find it. The rest of the project can be found at
https://github.com/iMillJoe/spell-checker
Upvotes: 0
Views: 1850
Reputation: 3069
Declare your word[LENGTH]
array outside of the loop, else it will just discard the word
pointer and free the allocated at the end of each cycle, create a new one. I don't think you want that, I think you would rather want that only when the if
condition does not get fulfilled.
I may not know what trieWordInsert
does, but I will assume that you'll need a 0
terminator.
word[LENGTH] = { 0 };
right before the for( ... ) { ... }
memset( word, 0, LENGTH);
inside the else
block therememory.h
or string.h
for the memset
if you haven't included either one of those by farAnd this should be it, I think...
Edit: After having learned how trieWordInsert
more or less issues the word
pushed in...
bool load( const char* dictionary )
{
if ( !rootNode )
{
rootNode = trieNodeCreate( );
if ( !rootNode )
{
printf( "could not allocate root node" );
return false;
}
}
// Open the file
FILE* fp = fopen( dictionary, "r" );
if ( fp == NULL )
{
printf( "could not open dictioanry %s\n", dictionary );
return false;
}
int index = 0;
char word[LENGTH];
for ( int c = fgetc( fp ); c != EOF; c = fgetc( fp ) )
{
if ( c != '\n' )
{
word[index] = c;
index++;
}
else
{
word[index] = 0;
trieWordInsert( word, rootNode );
index = 0;
wordCount++;
}
}
fclose( fp );
if ( wordCount )
{
return true;
}
return false;
}
Upvotes: 2
Reputation: 8313
I think you didn't end the word with a '\0'
char word[LENGTH];
if (c != '\n' )
{
word[index] = c;
index++;
}
else
{
word[index] = '\0'; //missing this one!!!
trieWordInsert(word, rootNode);
index = 0;
wordCount ++;
}
I think you better use fscanf
and read the file word by word.
Upvotes: 1