So I've managed to properly handle and prepare all the data I want to store (in this case words from a text file) in an ADT style binary search tree and insert without any memory leaks.
My problem now is making sure that no repeated words are added to the tree. To do this, I am using a retrieve function that was given to us from our text which returns a pointer to the data within the node which contains the desired key if found, or NULL if not found.
If it returns NULL, then I know that the word is not yet in the tree and I allocate memory for a pointer to the struct to store it and call the insert function (also from the book).
Otherwise, I use the return value to update the counter field in the data.
Code:
void addWord (BST_TREE *list, char *string, int length)
{
WORD *wordPtr;
void *dataPtr;
dataPtr = BST_Retrieve(list, (void*)string);
if(!dataPtr)
{
wordPtr = createWord();
wordPtr->word = (char*) calloc(length, sizeof(char));
strncpy(wordPtr->word, string, length);
if(BST_Insert(list, (void*)wordPtr))
printf("%s was inserted succesfully (%d)\n", wordPtr->word, wordPtr->count);
else
printf("Error! Could not insert\n");
}
else{
wordPtr = (WORD*)dataPtr;
wordPtr->count++;
printf("%s was found in the list (%d)\n", wordPtr->word, wordPtr->count);
}
return;
}//addWord
My program continues to crash after the first iteration of insertion and it is driving me crazy. To my knowledge, the logic I have implemented should work, but obviously I am missing something.
Here is how I am calling it
Code:
void getData (BST_TREE *wordBST)
{
FILE *fp1;
char buf[BUFSIZ], *pBuf;
int length;
//Open file
fp1 = fopen(FILE1, "r");
if(!fp1){
printf("Error opening file!\n");
system("pause");
exit(101);
}
//Read text from file
while(fscanf(fp1, "%s", &buf) != EOF){
length = strlen(buf) + 1;
if(!isalpha(buf[length - 2])){//Get rid of punctuation
buf[length - 2] = '\0';
length--;}
for(pBuf = buf; pBuf < buf + length - 1; pBuf++)//Get all lowercase
*pBuf = tolower(*pBuf);
addWord(wordBST, buf, length);
}
fclose(fp1);
return;
}//getData
Any and all feedback is appreciated