【问题标题】:Memory exception When inserting a value into a hash table将值插入哈希表时出现内存异常
【发布时间】:2022-01-25 04:29:45
【问题描述】:

内存异常在向哈希表中插入值时,我需要构建一个将值插入到哈希表中的函数,但存在内存问题,因为链向我抛出了异常 我想要一个解决方案

哈希表.h

struct HashTableElement
{
    int key;
    LinkedList* chain;
};

typedef struct HashTable HashTable;

struct HashTable
{
    HashTableElement* hashTable;
    int hashFunction;
    int tableSize;
    int cellsTaken;
    int numOfElements;
};

链表.h

typedef struct LinkedList LinkedList;

struct LinkedList {
    char* data;
    LinkedList* next;
};

哈希表.c

HashTable* initTable(int tableSize, int hashFunction)
{

    HashTable* table = (HashTable*)malloc(sizeof(HashTable));
    table->tableSize = tableSize;
    table->hashFunction = hashFunction;
    if (table == NULL || tableSize < 1)
    {
        printf("EROR with malloc in initTable.");
        exit(1);
    }
    table->hashTable = malloc(sizeof(HashTableElement) * tableSize);

    int i;
    for (i = 0; i < hashFunction; i++) {
        table->hashTable[i].key = NULL;
        table->hashTable[i].chain = NULL;
    }
    return table;
}
int insert(HashTable* ht, char* str)
{
    HashTable* temp;
    int h = hash(str, ht);
    int i = 0;
    while (ht->hashTable[h].key != 0 && (i < ht->tableSize)) {

        if (ht->hashTable[h].key == *str) {
            ht->hashTable[h].key = *str;
            return; /* break is intended to quit the loop, but actually we want to exit the function altogether */
        }

        h = (h + 1) % ht->tableSize; /* changed 11 to the size specified */
        i++; /* advance the loop index */
    }
    if (ht->hashTable[h].key == 0) {
        ht->hashTable[h].chain->data = *str;
        return 1;
    }
    return 0;
}

ht->hashTable[h].chain->data = *str; 中插入函数的问题 我该如何解决那里的异常?

【问题讨论】:

  • 你应该检查if (table == NULL... 之前 table-&gt;
  • 奇怪的是你 table-&gt;hashtable = malloc(...tablesize,但随后使用 for (i = 0; i &lt; hashFunction; i++) ... 中的 hashfunction 值循环其元素你的数组的边界。在那里循环tablesize 更有意义。
  • 您确定您的hash 函数将返回一个在您的hashtable 范围内的h 值吗?没问题,但ht-&gt;hashTable[h].key = *str; 没用,因为您只是在上面的行中检查了它们是否相等。

标签: c hashtable


【解决方案1】:

我建议在继续实现哈希表之前先学习一门基本的 C 编程课程。 有很多错误,只是一般的奇怪的东西,我的帽子:

  • 您正在将一个 int(键)初始化为 NULL,它是一个指针。
  • 您正在初始化“tableSize”数组中的“hashFunction”元素(变量错误?)
  • 您只是将字符串的第一个字符存储为键。
  • if 语句检查您的键是否等于字符串的第一个字符,如果是,则再次将其设置为等于该值,以防万一返回之前是荒谬的。
  • 使用 2 个循环索引(h 和 i 似乎都是多余的)。

除了这些基本问题之外,您要问的问题是链将为 NULL。如果使用 ...chain->data,则会取消引用 NULL 指针,这很糟糕。

真正的问题是您似乎不了解链表和 C 内存管理,这是实现更复杂结构(例如哈希表)的先决条件,所以我建议您退后一步,从像这样继续之前的基础 C 课程。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2021-03-09
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
相关资源
最近更新 更多