【问题标题】:Error when inserting in HashTable在 HashTable 中插入时出错
【发布时间】:2018-10-29 17:11:51
【问题描述】:

当尝试在哈希表中插入字符串时,即使哈希函数计算的位置是有效的,我也会收到分段错误错误。

#define initial_size 23

typedef struct user{
    char nick[6];
    char name[26];
}user;

typedef struct hashtable{
    int size;
    user **buckets;
}hashtable;

int elements = 0;
int size = initial_size;

hashtable * create() {
    hashtable *htable = malloc(sizeof(htable));
    htable->size = initial_size;
    htable->buckets = calloc(initial_size, sizeof(htable->buckets));
    return htable;
}

int hash(char *string) {
    int hashVal = 0;
    for( int i = 0; i < strlen(string);i++){
        hashVal += (int)string[i];
    }
    return hashVal;
}


void insert(hashtable *HashTable, char *name, char *nick){
    HashTable = resize_HashTable(HashTable);
    int hash_value = hash(nick);
    int new_position = hash_value % HashTable->size;
    if (new_position < 0) new_position += HashTable->size;
    int position = new_position;
    while (HashTable->buckets[position] != 0 && position != new_position - 1) {
        position++;
        position %= HashTable->size;
    }
    strcpy(HashTable->buckets[position]->name, name);
    strcpy(HashTable->buckets[position]->nick, nick);
    HashTable->size = HashTable->size++;
    elements++;
}

错误在这几行:

strcpy(HashTable->buckets[position]->name, name);
strcpy(HashTable->buckets[position]->nick, nick);

使用此输入时:

int main(){
    hashtable *ht = create();
    insert(ht, "James Bond", "zero7");
    return 0;
}

我不明白为什么会发生这种情况,因为在上述情况下,计算的哈希位置将为 20,而哈希表的大小为 23。

有解决问题的技巧吗?提前致谢。

【问题讨论】:

  • 可能是您没有为namenick 分配空间,只为它们的指针分配空间。
  • 那个或者你分配桶的 calloc 是关闭的。
  • @fredrik 我之前尝试过用 malloc 替换 calloc,但错误一直在发生,所以我不认为它来自那里。当您提到为 name 和 nick 分配空间时,插入时使用的 strcpy 不是已经这样做了吗?
  • 你在做malloc(sizeof(htable))这应该是malloc(sizeof(hashtable))
  • 将整行替换为hashtable *htable = (hashtable*)malloc(sizeof(hashtable));

标签: c arrays data-structures segmentation-fault hashtable


【解决方案1】:

您应该为 create() 函数中的每个存储桶分配内存。

hashtable * create() {
hashtable *htable = malloc(sizeof(htable));
htable->size = initial_size;
htable->buckets = calloc(initial_size, sizeof(htable->buckets));
int i;
for(i=0;i<initial_size;i++)
    htable->buckets[i] = (user*)malloc(sizeof(user));
return htable;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多