由于while循环中的条件,导致Segmentation错误
Getting a Segmentation fault because of conditions in while loop
我用字符串数组制作了一个哈希表,在插入中,我有一个while语句,用于处理冲突和环绕。我已经试过了,似乎只有在使用条件语句时才会出现分段错误11。这是我的while循环:
while (numElm != length)
{
numProbes = 0;
int index = hash( newGuest );
//handles collision and wraparound
while (hashArray[index] != " " && hashArray[index] != "-1")
{
++index;
index %= length;
numProbes = numProbes + 1;
}
//sets the array at the index eqaul to data
hashArray[index] = newGuest;
cout << newGuest << " has been inserted at index: " << index << " using " << numProbes << " probes";
break;
}
当第二个while循环以两个条件语句开始时,就会出现问题。有人能告诉我为什么会发生这种事吗?
编辑程序的其余部分
#include <cassert>
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <string>
#include "HashTable.h"
using namespace std;
//typedef double value_type;
HashTable::HashTable( int tableLength )
{
tableLength = 114;
string *hashArray = new string[tableLength];
length = tableLength;
numElm = 0;
for(int i = 0; i < length; i++)
{
hashArray[i] = " ";
}
}
// Returns an array location for a given item key.
int HashTable::hash( string itemKey )
{
int value = 0;
for (int i = 0; i < itemKey.size(); i++ )
{
value += itemKey[i];
}
return (value * itemKey.length() ) % length;
}
// Adds an item to the Hash Table.
void HashTable::insertGuest( string newGuest )
{
// int index = hash( newGuest );
//hashArray[ index ].insertGuest( newGuest );
// cout << newGuest << " has been inserted at index: " << index;
// string s = " ";
while (numElm != length)
{
numProbes = 0;
int index = hash( newGuest );
//handles collision and wraparound
while (hashArray[index] != " " && hashArray[index] != "-1")
{
++index;
index %= length;
numProbes = numProbes + 1;
}
//sets the array at the index eqaul to data
hashArray[index] = newGuest;
cout << newGuest << " has been inserted at index: " << index << " using " << numProbes << " probes";
break;
}
}
// De-allocates all memory used for the Hash Table.
HashTable::~HashTable()
{
delete [] hashArray;
}
//#endif
您没有初始化成员变量hashArray
,在构造函数中只有局部的变量hashArray
。类中的hashArray
保持未初始化状态,使用时会导致崩溃。要修复,请更换
string *hashArray = new string[tableLength];
带有
hashArray = new string[tableLength];
这解决了问题。在其他方面,代码有很多风格和代码方面的问题,但我希望您能继续学习自己解决这些问题。祝你好运
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 执行函数时导致崩溃的变量
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 使用 LuaBridge 将 LuaJIT 绑定到C++会导致"PANIC: unprotected error"
- C++/传递值导致#DEN
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- C++使用params创建线程函数会导致转换错误
- 为什么加载SDF会导致Mobilizer创建闭环错误
- 使用Vulkan hpp vk::enumerateInstanceVersion()会导致segfault
- 处理除以零会导致<csignal>意外行为
- 使用++运算符会导致意外的结果
- 换位表导致测试失败(但在游戏中运行良好)
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 导致Segmentation错误的结构中的矢量
- 将double打印到std::cout会导致Segmentation fault(C++)
- 由于while循环中的条件,导致Segmentation错误
- 取消引用会导致Segmentation错误
- 当g++静态链接pthread时,导致Segmentation错误,原因何在
- 引用字符串参数导致Segmentation错误