When removing an element from a hashtable, I need to traverse through linked-lists for elements that collide. I am using pointer operations to do this, and my linked list is in the form of bucket_t
. The problem I am facing is that when I try to save the location of the first ht->bucket[I]
, that value changes along with the others, so at the end of the function, my head is right at the spot of next
and results in a segmentation fault. I am new to working with pointers like this in c, and I apologize if my explanation is bad, but I think the code is fairly simple for you guys to see what I am trying to achieve:
void ht_del(hashtable_t *ht, char *key) {
bucket_t *last=NULL, *next=NULL, *head=NULL;
unsigned long i;
for(i = 0; i < ht->size; i++){
head = ht->buckets[i];
next = ht->buckets[i];
while(next && next->key && strcmp(next->key,key)!=0){
last = next;
next = next->next;
printf("\nvisiting next\n");
printf("key = %s\n", head->key);
}
if(next && next->key && strcmp(next->key,key)==0){
printf("key found, removing key = %s, val = %s:", next->key, next->val);
free(next->key);
free(next->val);
if(next->next){
last->next = next->next;
printf("Last->next ->key = %s\n", last->next->key);
}
else{
free(next->next);
printf("end of the line\n");
}
free(next);
printf("head key = %s", head->key);
}
}
}
Additionally, to help understand the structs im using:
typedef struct hashtable hashtable_t;
typedef struct bucket bucket_t;
struct bucket {
char *key;
void *val;
bucket_t *next;
};
struct hashtable{
unsigned long size;
bucket_t **buckets;
};