简体   繁体   中英

Segmentation Fault in Hash Table - C

I am currently working on a programming assignment for class. I am getting a seg fault in one of my functions and can not come to the root of the issue. I have done my best and found that the seg fault occurs in "if(myNode->key==key)". Any wise words will help!

struct node*searchForPerson(const char *value){
int key=convertToKey(value);
struct node *myNode;

int i=0;
int j = (key % 8)+(i*(key%5));


while (i < size - 1 && hashTable[j].head != NULL && hashTable[j].index != key ) {
    i++;
    j=(key % 8)+(i*(key%5));
}
myNode=hashTable[j].head;

if(myNode->key==key) {

    printf(" found\n");
    return myNode;
}
else{
printf("not found\n");
    return NULL;
    }
}

I thought that the root of the issue may be my insert to hash function:

void insertToHash(int key,  char *value){

int i = 0;
int j = (key % 8)+(i*(key%5));
struct node *newnode = createNode(key, value);
/*head of list for the bucket with index "hashIndex"*/
if (!hashTable[j].head) {
    hashTable[j].head = newnode;
    hashTable[j].count=1;
    return;
}

while (i < size - 1 && hashTable[j].head != NULL) {
    i++;
    j=(key % 8)+(i*(key%5));
}
//adding new node to the list
hashTable[j].head=newnode;
hashTable[j].count++;
return;



hashTable[j].head = newnode;
hashTable[j].count++;
}

You should add an if statement which ensures that hashTable[j].head is not NULL .

Keep in mind that your while loop condition is ANDing 3 conditions, so if any one of them becomes false, the loop will exit. In particular, immediately after your loop you don't know if it exited because

  1. i is now greater than or equal to size - 1
  2. hashTable[j].head is now equal to NULL
  3. hashTable[j].index is now equal to key

If the case is (2), then myNode will be NULL so myNode->key will be dereferencing a null pointer, resulting in a segfault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM