I'm new to C I'm trying to check if a word is in my hash table or not. But I'm getting a segmentation fault.
This is my code for the function It should return true if the word is found or false if not
bool check(const char *word)
{
// Hashing the word
unsigned int hc = hash(word);
// Creating a node for traversing
node *ch = malloc(sizeof(node));
// Traversing
ch->next = table[hc];
C = false;
while (ch->next != NULL)
{
if (strcasecmp(ch->word, word) == 0)
{
c = true;
break;
}
ch = ch->next;
}
return c;
}
CodePudding user response:
For starters neither the variable C
used in this statement
C = false;
nor the variable c
used in this statement
c = true;
are declared.
This allocation of a node
node *ch = malloc(sizeof(node));
does not make a sense and produces a memory leak.
Also it is unclear whether for the given string the function hash
returns a valid value of an index in the array table
.
Provided that the function hash
indeed returns a valid index then the function check
can be defined the following way
bool check( const char *word )
{
// Hashing the word
unsigned int hc = hash( word );
// Traversing
node *head = table[hc];
while ( head != NULL && strcasecmp( head->word, word ) != 0 )
{
head = head->next;
}
return head != NULL;
}
CodePudding user response:
There are several issues with your code:
- You only need to
malloc
when you create a node, for example when you insert an item into the table. If you just want to traverse the list in a bucket, create a pointer variable that visits all elements one by one. That variable is either a pointer to an existing node in the list orNULL
. - When you traverse the list, you look at the nodes in isolation. You don't need to access
next
until you move to the next node.
Your function might look like this:
bool check(const char *word)
{
unsigned int hc = hash(word);
node *ch = table[hc];
while (ch != NULL) {
if (strcasecmp(ch->word, word) == 0) {
return true;
}
ch = ch->next;
}
return false;
}
This should work provided that hash(word)
produces valid hash table indices and that all head nodes of the bickets have been initialize to ´NULL`.