谁能告诉我为什么它显示"runtime error"?

Can anyone please tell me why is it showing "runtime error"?

本文关键字:runtime error 显示 告诉我 为什么      更新时间:2023-10-16

我正在尝试实现哈希表,但在createHashTable()函数的for循环中遇到运行时错误。有人能告诉我为什么它显示这个"运行时错误"吗?是StackOverflow错误吗?

#include <iostream>
using namespace std;
#define LOAD_FACTOR 20
struct ListNode{
    int data;
    struct ListNode *next;
};
struct HashTableNode{
    int bCount; // number of elements in the block
    struct ListNode *next;
};
struct HashTable{
    int tSize;  // table size
    int count;  // total number of elements in the table
    struct HashTableNode **hashTableNodeArray;
};
int hashFunction(struct HashTable *h, int data){
   return data % h->tSize;
}
struct HashTable * createHashTable(int numberOfElements){
   struct HashTable *h = new HashTable;
   h->count = 0;
   h->tSize = numberOfElements / LOAD_FACTOR;
   h->hashTableNodeArray = new HashTableNode *[h->tSize];
       for(int i = 0; i < h->tSize; ++i){
       // this is where it is showing runtime error
       h->hashTableNodeArray[i]->bCount = 0;
       h->hashTableNodeArray[i]->next = nullptr;
   }
   return h;
}
void deleteHashTable(struct HashTable *h){
   struct ListNode *node, *tmp;
   for(int i = 0; i < h->tSize; ++i){
       node = h->hashTableNodeArray[i]->next;
       while(node != nullptr){
           tmp = node;
           node = node->next;
           delete tmp;
       }
   }
   delete[] h->hashTableNodeArray;
   delete h;
}
int main(int argc, char **argv){
   struct HashTable *h = createHashTable(220);
   deleteHashTable(h);
   return 0;
}
h->hashTableNodeArray = new HashTableNode *[h->tSize];

这会分配一个指针数组,但不会分配实际的hashtablenodes。在下面的循环中,您尝试向它们写入,这是未定义的行为。

你在你的循环中失踪了:

h->hashTableNodeArray[i] = new HashTableNode;

问题就在这里:

h->hashTableNodeArray = new HashTableNode *[h->tSize];
for(int i = 0; i < h->tSize; ++i){
    // this is where it is showing runtime error
    h->hashTableNodeArray[i]->bCount = 0;
    h->hashTableNodeArray[i]->next = nullptr;
}

您分配了一个指针数组,但实际上并没有使指针指向任何有效的位置,这意味着它们的值是不确定的(实际上似乎是随机的)。然后,您继续取消引用这些未初始化的指针,并使用指针写入内存,而不知道将在内存中写入的位置。

这会导致未定义的行为,很可能会导致崩溃。

解决方案?要么不使用指针,要么显式地为指针分配内存。我的建议是完全停止使用指针,创建适当的复制和移动构造函数,而使用std::vector