-1
我有一個散列表,它是一個桶指針數組(節點在這個項目中被稱爲桶)。散列表使用鏈接列表鏈接來避免衝突。這裏是我的數據結構:Valgrind給出無效的免費錯誤信息
typedef struct bucket {
char *key;
void *value;
struct bucket *next;
} Bucket;
typedef struct {
int key_count;
int table_size;
void (*free_value)(void *);
Bucket **buckets;
} Table;
Valgrind是給我一個無效的free()的錯誤信息,在行:table->free_value(curr->value);
在該方法中:
/* Removes a bucket consisting of a key and value pair */
int remove_entry(Table * table, const char *key) {
unsigned int hc = 0;
int found = 0;
Bucket *curr;
Bucket *prev;
if (table == NULL || key == NULL) {
return FAIL;
}
hc = hash_code(key)%(table->table_size);
if (table->buckets[hc] != NULL) {
curr = table->buckets[hc];
prev = NULL;
while (curr != NULL) {
if (strcmp(curr->key, key) == 0) {
found = 1;
if (table->free_value != NULL && curr->value != NULL) {
table->free_value(curr->value);
if (curr == table->buckets[hc]) {
table->buckets[hc] = curr->next;
free(curr->key);
free(curr);
curr = NULL;
(table->key_count)--;
return SUCC;
}
prev->next = curr->next;
free(curr->key);
free(curr);
curr = NULL;
(table->key_count)--;
return SUCC;
} else {
if (curr == table->buckets[hc]) {
table->buckets[hc] = curr->next;
free(curr->key);
free(curr);
curr = NULL;
(table->key_count)--;
return SUCC;
}
prev->next = curr->next;
free(curr->key);
free(curr);
curr = NULL;
(table->key_count)--;
return SUCC;
}
}
prev = curr;
curr = curr->next;
}
}
if (found == 0) {
return FAIL;
}
return SUCC;
}
我不知道它爲什麼這麼說。這裏是我的put()方法:
/* Puts a key value pair in. If the key exists, the value is updated, otherwise the pair is added. */
int put(Table *table, const char *key, void *value) {
unsigned int hc = 0;
Bucket *curr;
Bucket *new_bucket;
char *copy_key;
if (table == NULL || key == NULL) {
return FAIL;
}
copy_key = malloc(sizeof(strlen(key) + 1));
if (copy_key == NULL) {
return FAIL;
}
strcpy(copy_key, key);
hc = hash_code(key)%(table->table_size);
if (table->buckets[hc] != NULL) {
curr = table->buckets[hc];
while (curr != NULL) {
if (strcmp(curr->key, key) == 0) {
if (curr->value != NULL && value != NULL) {
table->free_value(curr->value); /* Getting the invalid free error here again */
}
curr->value = value;
free(copy_key);
return SUCC;
}
curr = curr->next;
}
curr = table->buckets[hc];
new_bucket = malloc(sizeof(*new_bucket));
if (new_bucket == NULL) {
free(copy_key);
return FAIL;
}
new_bucket->value = value;
new_bucket->key = copy_key;
new_bucket->next = curr;
table->buckets[hc] = new_bucket;
(table->key_count)++;
return SUCC;
} else if (table->buckets[hc] == NULL) {
new_bucket = malloc(sizeof(*new_bucket));
if (new_bucket == NULL) {
free(copy_key);
return FAIL;
}
new_bucket->value = value;
new_bucket->key = copy_key;
table->buckets[hc] = new_bucket;
table->buckets[hc]->next = NULL;
(table->key_count)++;
return SUCC;
}
free(copy_key);
return FAIL;
}
任何幫助,將不勝感激。謝謝。
我不認爲你給了我們完整的valgrind錯誤。無效免費進來了幾個品種(免費的指針,從來沒有分配;雙免費;頭/拖車損壞等)。 – abelenky