微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C哈希表实现中的分段错误

如何解决C哈希表实现中的分段错误

我正在做一个练习,我必须在 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;

ma​​in.c(测试代码):

#include "hash_table.h"

int main(){
    ht_table* table = ht_new();
    ht_del(table);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。