【问题标题】:Receiving "Segmentation fault" when attempting to insert keys in hash table尝试在哈希表中插入键时收到“分段错误”
【发布时间】:2019-12-10 15:14:04
【问题描述】:

我正在尝试使用我已经制作的链表结构在 C 中实现开放散列。链表结构完美运行,但是在我的哈希表结构中尝试使用它们时,我经常收到“分段错误(核心转储)”

我已经检查以确保我使用了正确的数据类型并且分配了正确的内存量。

typedef struct LinkedList LinkedList;

LinkedList* createLinkedList(){
    LinkedList* rslt = malloc(sizeof(Node*)); //Allocate memory for LL
    //rslt->head = calloc(1,sizeof(Node*)); //Allocate memory for head with default Node* value (NULL)
    return rslt;
}

void add_end_LinkedList(LinkedList* x, int v){

    //Special case: LinkedList is empty
    if(x->head == NULL)
        x->head = createNode(v);

    else{
        //Traversing to end of list
        Node* p;
        for(p = x->head; p->next != NULL; p = p->next){1;}
        p->next = createNode(v);
    }
}

void add_beg_LinkedList(LinkedList* x, int v){
    Node* p;

    //Special case: LinkedList is empty
    if(x->head == NULL)
        x->head = createNode(v);

    else{
        p = createNode(v);
        p->next = x->head;
        x->head = p;
    }
}

int isIn_LinkedList(LinkedList* x, int v){
    for(Node* p = x->head; p != NULL; p = p->next){
        if(p->val == v) return 1;
    }

    return 0;
}

void print_LinkedList(LinkedList* x){
    for(Node* p = x->head; p != NULL; p = p->next){
        print_Node(p);
        printf(", ");
    }
    printf("\n");
    return;
}

//HASHTABLE_____________________________________________________________

struct HashTable{
    LinkedList** table;

};

typedef struct HashTable HashTable;

HashTable* createTable(){
    HashTable* rslt = {calloc(9,sizeof(LinkedList*))};

    for(int i = 9; i < 9; i++)
        rslt->table[i] = createLinkedList();

    return rslt;
}

int compute_hash(int v){
    return v%9;
}

int isIn_HashTable(HashTable* x, int v){
    return isIn_LinkedList(x->table[compute_hash(v)], v);
}

int insert_HashTable(HashTable* x, int v){
    if(isIn_HashTable(x, v)){
        return 0;
    }

    add_beg_LinkedList(x -> table[compute_hash(v)], v);
    return 1;
}

int main(void){
    HashTable* a = createTable();
    insert_HashTable(a, 6);
    return 0;
}

createTable() 不会引发任何运行时错误。但是任何其他 HashTable 函数都可以。我无法访问表中的链接列表。

【问题讨论】:

标签: c memory hash linked-list hashtable


【解决方案1】:

Rslt 是一个指针。您不能像初始化 struts 那样初始化它。从函数返回后,rslt指针将在以下代码中失效

 HashTable* createTable(){
     HashTable* rslt = {calloc(9,sizeof(LinkedList*))};

{..} 不是动态内存分配。先尝试malloc rslt

     HashTable *rslt = malloc(sizeof(HashTable));
     rslt->table = calloc...

【讨论】:

    猜你喜欢
    • 2014-03-28
    • 2021-01-19
    • 2013-12-25
    • 2016-03-03
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    相关资源
    最近更新 更多