The code is working for loading large dictionaries most of the times but when i am trying to load a small dictionary i get the message that dictionary couldn't be loaded, while after that when i am trying to load large dictionary i get segmentation fault. I have declared node *head=NULL; as a global variable, so i can use it for my search function. Below i am giving you the code. If anyone can look at it and tell me why i am getting this message it will be great! Thank you!!
node *head=NULL; //I have declare this as a global variable.
bool load(const char* dictionary) {
FILE *fp=fopen(dictionary, "r");
if (fp==NULL)
{
printf("File dictionary could not be opened.\n");
return false;
}
while (!feof(fp))
{
node *new_node=malloc(sizeof(node));
fscanf(fp, "%s", new_node->word);
int h=hash_function(new_node->word, strlen(new_node->word));
if (hash_table[h]==NULL)
{
hash_table[h]=new_node;
head=hash_table[h];
head->next=NULL;
}
else if (hash_table[h]!=NULL)
{
new_node->next=head->next;
head->next=new_node;
}
}
if(feof(fp))
{
return true;
fclose(fp);
}
return false;
fclose(fp);
}
hash function:
int hash_function(const char *key, int M) {
unsigned long h;
const char *us;
us = (const char *) key;
h=0;
while (*us !=0) { h=(h * BASE + *us)%M; us++; }
return h;
}
valgrind
andgdb
to figure out which line exactly causes the segfault?