I have implemented a hashmap in C and after quite a bit of work I have gotten everything working great… except for my release routine.
My structs are setup like so:
struct hashmap_element {
int value;
int key;
int used;
struct hashmap_element* next;
};
struct hashmap {
int table_size;
int current_size;
struct hashmap_element* table;
};
And my current non-working release routine looks like this:
void hm_release(struct hashmap* hm) {
hashmap_element* tmp;
hashmap_element* curr_itr;
for(int x=0; x<hm->table_size; x++) {
curr_itr = &hm->table[x];
while (curr_itr) {
tmp = curr_itr->next;
free(curr_itr);
curr_itr = tmp;
}
}
free(hm->table);
free(hm);
}
Unfortunately this current segvaults after its first run. I seem to be having trouble getting my ‘curr_itr’ to lock onto the first chain of each bucket in the array. I’m fairly new to using dynamic memory like this in C and have been stuck on this for a few days now.
Everything is being initialized properly as far as I can tell. Here for example is my hashmap init function.
hashmap* hm_initialize() {
hashmap* hm = malloc(sizeof(hashmap));
hm->table = (hashmap_element*) calloc(INIT_SIZE, sizeof(hashmap_element));
hm->table_size = INIT_SIZE;
hm->current_size = 0;
// init the buckets
for (int x=0; x < hm->table_size; x++) {
hm->table[x].used=0;
hm->table[x].value=0;
hm->table[x].key=0;
hm->table[x].next=NULL;
}
return hm;
}
Any suggestions/comments would be greatly appreciated. Please let me know if you need more of my code.
Thank you.
You start freeing too early,
The
hashmap_elementhm->table[x]was notmalloced, so you shouldn’tfreeit.frees only the (hopefully)
mallocedhashmap_elements after the first in the bucket.