谁能告诉我为什么它显示"runtime error"?
Can anyone please tell me why is it showing "runtime error"?
我正在尝试实现哈希表,但在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
。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 使用 LuaBridge 将 LuaJIT 绑定到C++会导致"PANIC: unprotected error"
- OpenMP卸载说'fatal error: could not find accel/nvptx-none/mkoffload'
- C++错误:"error: int aaa::bbb is protected within this context"
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 使用 cmake 的 LLVM 构建在 tsan_libdispatch_mac.cc 期间失败; "Error: conflicting types for ..."
- C++ "error: invalid use of void expression"
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- "runtime error: addition of unsigned offset to 0x129000a0 overflowed to 0x12900088"
- 为什么我的代码中出现'Runtime Error - SIGSEGV'?
- C++ dynamic_cast runtime-error
- 错误"Runtime error"
- 如何修复不影响性能的"runtime error"?
- 谁能告诉我为什么它显示"runtime error"?
- Lua+Luabind,"runtime error"后堆栈顶部没有错误信息
- 如何解决C代码中"runtime error exitcode 6"报告的错误?
- 在范围结束后提升共享指针"runtime error"
- C++ 'Runtime error time: 0 memory: 3452 signal:11'