问题描述
我正在做一个练习,我必须在 C 中创建一个哈希表实现。到目前为止,我已经设置了基本的数据结构,但是我遇到了一个我似乎无法做到的分段错误查明。我已经设法弄清楚 ht_del()
是问题所在,但除此之外我还不确定。
如果这很重要,这是我用来编译的命令:gcc main.c hash_table.c -o main -w
hash_table.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash_table.h"
static ht_item* ht_new_item(const char* k,const char* v){
ht_item* item = malloc(sizeof(ht_item));
item->key = strdup(k);
item->value = strdup(v);
return item;
}
static void ht_del_item(ht_item* item){
free(item->key);
free(item->value);
free(item);
}
ht_table* ht_new(){
ht_table* table = malloc(sizeof(ht_table));
table->size = 53;
table->count = 0;
table->items = calloc((size_t) table->size,sizeof(ht_item*));
return table;
}
void ht_del(ht_table *table){
for(int k = 0; k < table->size; ++k){
ht_item* item = table->items[k];
if(item != NULL) ht_del_item(item);
}
free(table->items);
free(table);
}
hash_table.h:
typedef struct {
char* key;
char* value;
} ht_item;
typedef struct {
int size;
int count;
ht_item** items;
} ht_table;
main.c(测试代码):
#include "hash_table.h"
int main(){
ht_table* table = ht_new();
ht_del(table);
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)