在特定索引处释放时出现分段错误

Segmentation fault when freeing at specific indices

在哈希表上 tutorial 之后,我实现了一种简化版本。但是,每当 delete_entry 在每 4 个索引(4、8、12 ...)上调用时,我都会遇到分段错误。否则,它工作正常

这是我的代码 运行:

#include <stdio.h>

typedef struct {
    int key;
    int value;
} entry;

typedef struct{
    int length;
    int count;
    entry** items;
} table;

entry *new_entry(const int, const int);
table *create_table();
void destroy_table(table *t);
void delete_entry(entry *e);
void table_insert(table *, const int, const int);

int main(){
    table *new_table = create_table();
    printf("[INFO] Created new table successfully!!\n");
    
    for(int i=0; i<16; i++){
        table_insert(new_table,i,i+i);
    }
    printf("[INFO] Inserted %d items\n",new_table->count);

    destroy_table(new_table);
    printf("[INFO] Destroyed table successfully!!\n");
    return 0;

}

table *create_table(){
    table *new_table = malloc(sizeof(table));
    if(new_table == NULL){
        printf("[WARNING] Malloc failure, returning NULL");
        return NULL;
    }
    new_table->length = 16;
    new_table->count = 0;
    new_table->items = calloc((size_t)new_table->length, sizeof(entry*));
    
    return new_table;
}

entry *new_entry(const int k, const int val){
    entry *new_item = malloc(sizeof(entry));
    if(new_item == NULL){
        printf("[WARNING] Malloc failure, returning NULL");
        return NULL;
    }
    new_item->key = k;
    new_item->value = val;
    
    return new_item;
}
void destroy_table(table *t){
    for(int i=0; i<t->count; i++){
        if(i== 4 || i == 8|| i==12) //Without this program terminates after 3rd index
            continue;
        entry *e = t->items[i];
        if (e != NULL){
            delete_entry(e);
        }
    }
    free(t->items);
    free(t);
}
void delete_entry(entry *e){
    free(e->key);
    free(e->value);
    free(e);
}

void table_insert(table *t, const int k, const int v){
    entry *e = new_entry(k, v);
    t->items[t->count] = e;
    t->count++;
}

尝试将 delete_entry() 替换为:

void delete_entry(entry *e){
    free(e);
}

释放整数 e->keye->value 的值可能会导致未定义的行为。您应该只对 malloc() 和朋友生产的对象使用 free()