0

I'm completely lost on this one. I can't see a problem with my check function but it never returns a match when using strcasecmp. I think the problem is probably in load() but I really have no idea what's wrong at this stage. My hash function works fine (I've tested it out) so that isn't the problem.

When I run the program on a smaller text, it will seg fault at a random point. Sometimes in the first few words, and sometimes it can run a small text such as "wordsworth.txt" withouth seg faulting.

Check function

bool check(const char *word)
{
//HASH WORD TO OBTAIN A HASH VALUE
int hashValue = hash(word);


//ACCESS LINKED LIST AT THAT INDEX IN THE HASH TABLE


while (table[hashValue]->next != NULL)
{
    //check if word is in linked list
    if (strcasecmp(table[hashValue]->word, word) == 0)
    {
        //if word matches, return true
        printf("MATCH FOUND\n");
        return true;
    }
    else
    {
        //if word doesn't match, check next value in linked list
        table[hashValue] = table[hashValue]->next;
    }
}

//if the words don't match, return false
printf("NOT A MATCH\n");
return false;
}

The problem could be in my load function.

bool load(const char *dictionary)
{

//OPEN DICT FILE and check if NULL
FILE *dictFile = fopen(dictionary, "r");
if (dictFile == NULL)
{
    printf("Could not open dictionary\n");
    unload();
    return false;
}

//READ STRINGS FROM FILE
//make buffer for new word, max word size is 45
char word[LENGTH + 1];
//repeat for all words in dictionary, until fscanf returns EOF
for (int c = fgetc(dictFile); c != EOF; c = fgetc(dictFile))
{
    fscanf(dictFile, "%c", word);

    //CREATE NEW NODE, allocate memory for it
    node *newNode = malloc(sizeof(node));
    if (newNode == NULL)
    {
        printf("Not enough memory\n");
        unload();
        return false;
    }

    //copy word into node using strcpy
    strcpy(newNode->word, word);
    newNode->next = NULL;

    //HASH WORD, use hash function
    hashNum = hash(newNode->word);

    //INSERT NODE INTO HASH TABLE (linked list)
    //check for collision in hash table
    if (table[hashNum] == NULL)
    {
        table[hashNum] = newNode;
    }

    //if collision, put node at start of the linked list
    else
    {
        //point new node at start of linked list
        newNode->next = table[hashNum];
        //make new node the start of linked list
        table[hashNum] = newNode;

    }

    //iterate number of words in dictionary by 1
    numWords++;

}

fclose(dictFile);
return true;
}

I'm completely stuck on this so any help will be appreciated.

0

In the check() function by modifying your head table in : table[hashValue] = table[hashValue]->next; you are losing access to the elements of the table. Try to create a new node pointer instead.

You must log in to answer this question.

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