gpt4 book ai didi

c - 从链表中正确删除元素?指针的内存错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:31 26 4
gpt4 key购买 nike

我正在实现一个具有 remove_entry 函数和 clear_table 函数的哈希表。现在我收到与 remove_entry 函数有关的内存读取错误。非常感谢您的帮助

这些是我的结构:

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;

这是我的功能:

int remove_entry(Table * table, const char *key){
unsigned int hc = 0;
Bucket *curr_b;
Bucket *next_b;

if(table == NULL || key == NULL){
return FAIL;
} else {
hc = hash_code(key)%(table->table_size);
if(table->buckets[hc] != NULL){
curr_b = table->buckets[hc];

/*Check the buckets in linked list*/
while(curr_b != NULL){
next_b = curr_b->next;

if(strcmp(curr_b->key,key) == 0){
free(curr_b->key);
if(table->free_value != NULL){
table->free_value(curr_b->value);
}
free(curr_b);
curr_b = NULL;
table->key_count--;
return SUCC;
} else {
curr_b = next_b;
}
}
return FAIL;
}
return FAIL;
}
}

内存泄漏发生在删除条目并尝试读取之后的表之后。我不认为我删除了正确的东西。

内存错误:

不知道如何从终端复制/粘贴,所以他们都说类似

Invalid read of size __
Address ____ is __ bytes inside a block of size ___ free'd

最佳答案

您需要考虑 table->buckets[hc] 是您释放的桶的情况。

free(curr_b->key); 之前添加:

if(curr_b == table->buckets[hc]) {
table->buckets[hc] = next_b;
}

就像现在一样,您释放了一个桶,但是 table->buckets[hc] 仍然指向它。所以下次你阅读它时,你正在阅读释放的内存。因此错误。

此外,您还需要跟踪前一个 桶,以便在删除桶时可以将前一个桶指向下一个桶。

关于c - 从链表中正确删除元素?指针的内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19620579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com