0

Here is my code for the load function. This function causes immediate segmentation fault on

if (hashtable[index] == NULL) { hashtable[index] -> next = new; }

bool load(const char* dictionary)
{
    // open dictionary
    FILE* dict = fopen(dictionary, "r");
    // check for openning error
    if (dict == NULL){
        printf("Could not open the dictionary");
        return 1;
    }
    char word[LENGTH + 1];
    char chewup; // to skip the line terminator

    while(true){
        // read a word from a dictionary
        fgets(word, sizeof(word), dict);
        if (!feof(dict)){
            chewup = getc(dict); // chew up new line terminator
            // determine index to put the word at
            int index = getHash(word);
            // allocate new node
            node* new = malloc(sizeof(node));
            // initialize new node
            strcpy(new -> word, word);
            new -> next = NULL;
            if (hashtable[index] == NULL) {
                hashtable[index] -> next = new;
            } else {
                new -> next = hashtable[index] -> next;
                hashtable[index] -> next = new;
            }    
        } else {
            break; // eof is reached
        }
    }
    return true;
}

Here are my hash table declaration, struct and hash function.

typedef struct node {
    char word[LENGTH + 1]; // +1 for /0
    struct node* next;
} node;

node* hashtable[500];

int getHash (const char* word)
{
    int hash = 0;
    int n;
    for (int i = 0; word[i] != '\0'; i++)
    {
        // alphabet case
        if(isalpha(word[i]))
            n = word [i] - 'a' + 1;

        // comma case
        else
            n = 27;

        hash = ((hash << 3) + n) % LENGTH;
    }
    return hash;
}

The index of the array is valid according to the debugger. Please, help me to understand what causes the issue? Thanks!

4
  • Can you please add the declarations for hashtable and the structure for each node? – Cliff B Dec 28 '16 at 11:39
  • Thanks for the reply! I've updated my question. – nkom Dec 29 '16 at 11:07
  • Still need to see the declaration for hashtable[ ] – Cliff B Dec 30 '16 at 2:14
  • I have updated the question :) – nkom Jan 1 '17 at 11:41
1

Knowing that hashtable[] is an array of pointers, it's clear. Look at the problem line:

if (hashtable[index] == NULL) { hashtable[index] -> next = new; }

If the array element is NULL, there has been no memory allocated to it, so no struct exists. The code attempts to assign new to a pointer inside a structure that doesn't exist (->next), so it generates a seg fault. The assignment has to be made to hashtable[index] itself, not hashtable[index]->next, which doesn't exist.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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