任何人都可以告诉我为什么它会显示“运行时错误”?

时间:2015-02-05 12:54:15

标签: c++ c++11

我正在尝试实现哈希表,但我在 createHashTable()函数的 循环中遇到运行时错误。任何人都可以告诉我为什么它显示这个“运行时错误”?是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;
}

2 个答案:

答案 0 :(得分:4)

h->hashTableNodeArray = new HashTableNode *[h->tSize];

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

你的循环中缺少:

h->hashTableNodeArray[i] = new HashTableNode;

答案 1 :(得分:2)

问题在于:

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;
}

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

这导致undefined behavior,很可能是您的崩溃。

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

相关问题