I am trying to build a BST ADT style containing data pointers to a WORD struct that I'm using for this application.
I've been going at this for a bit and I have yet to understand what I am doing wrong..
The fields of the struct are being handled correctly before insertion, but whenever I call the insert function it fails to execute properly and my program crashes.
Here is what I've written for this:
Code:
/*
list is a pointer to the header of the BST, string is a dynamically
allocated string (the word field), and length is the strlen of the
string
*/
void addWord (BST_TREE *list, char *string, int length)
{
WORD *wordPtr;
wordPtr = (WORD*)BST_Retrieve(list, (void*)string);
//If the key (string) is found in the BST, BST_Retrieve returns a pointer to the data in the
//node containing the key, otherwise it returns NULL
if(!wordPtr)//if the key is not found
{
wordPtr = createWord();//allocate memory for new WORD pointer
wordPtr->word = (char*) calloc(length + 1, sizeof(char));
strncpy(wordPtr->word, string, length);
if(BST_Insert(list, (void*)wordPtr))//Insert to BST
printf("%s was inserted succesfully (%d)\n", wordPtr->word, wordPtr->count);
else
printf("Error! Did not insert\n");
}
else{//if key is found
wordPtr->count++;//add to count, # of times key appears in the input (text file)
printf("%s was found in the list (%d)\n", wordPtr->word, wordPtr->count);
}
return;
}
I am calling this in a loop from another function. Everything functions properly until I call the BST ADT functions, BST_Retrieve, BST_Insert:
Code:
while(fgets(buf, sizeof(buf), fp1)){//Read full line into buffer string
length = strlen(buf);
if(length > 1){//Check for lines with text
pFirst = &buf[0];
for(pLast = buf + 1; pLast < buf + length; pLast++)
{
if(*pLast == ' ' || *pLast == '\n'){//Check for spaces or newline
temp_length = strlen(pFirst) - strlen(pLast);
if(temp_length > 0)
{
temp = formatString(pFirst, &temp_length);
printf("%s(%d)\n", temp, strlen(temp));
addWord(wordBST, temp, temp_length);//Insert to BST
free(temp);
pFirst = pLast + 1;//Reset initial pointer position
}
else
pFirst = pLast + 1;//Condition for empty strings
}
}
}
}
Can anyone please help me figure out why this isn't working?
Any and all feedback is appreciated