Hash table in C always yields Seg fault

143 views Asked by At

I am trying to develop a hash table in the C Programming Language which always fails with seg fault. I am trying to do seperate chaining so I created a struct which has two properties: word and next. The word is a char* and next a pointer to the next node, eventually creating a hash table that conatains an array of linked list.

typedef struct node 
{
    char* word;
    struct node* next;

}node;

node* table[26]; 

After this I am indexing into the table by using a hashing function which simply indexes into the table.

Do you have a fix?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h>

typedef struct node 
{
    char* word;
    struct node* next;

}node;

node* table[26]; 


int hash(char* key);
void index();

int main(int argc, char* argv[])
{
    index();

    return 0; 
}

int hash(char* key)
{
    int hash = toupper(key[0]) - 'A';
    int res = hash % 26;

    return res;
}

void index()
{   
    printf("Insert a word: ");
    char* k = GetString();    


    node* predptr = malloc(sizeof(node));
    node* newptr = malloc(sizeof(node));

    for(int i = 0; i < 26; i++)
    {
        if(hash(k) == i)
        {
            predptr = table[0];

            predptr->next = newptr;

            newptr = predptr;

            break;
        }

        else
        {

        }
    }


}
3

There are 3 answers

0
pmg On
typedef struct node 
{
    char* word;
    struct node* next;

}node;

node* table[26]; 

table is an array of 26 pointers, all initialized to NULL.

Specifically table[0] is a NULL pointer and you try to dereference it

            predptr = table[0];

            predptr->next = newptr; // dereference NULL pointer
            // NULL->next
1
Ashalynd On

You created a table of 26 pointers to node structure, but did not allocate memory for them. Also, it is not clear what your GetString() method does and how the memory for the strings returned by it is managed. You have to use your (incomplete) index method (provided that you properly allocate necessary objects there) instead of just calling table[ha]->word = word; which segfaults because tabel[ha] does not point anywhere.

0
sonus21 On
  1. If you are doing hashing on word then change hashing function as

    int hash(char *k){ int i=0; for (;i<strlen(k) ;++i ){ //apply hashing technique } }

  2. Your table has 26 NULL pointers , when you use

    predptr = table[0]; predptr->next = newptr;

here predptr become NULL and then you are looking for it's next pointer which leads to segmentation fault .

  1. To improve index performance you don't have to search for hashed index ,just goto that index < (No of maxm entries ) and follow it's pointer if it's null then add this word here it self else follow it's next pointer .