c++ - Push_front 段错误 11 C++

标签 c++ segmentation-fault

我尝试环顾四周并尝试了所有解决方案,但我似乎无法解决我的问题。我知道我在 push_front 线上遇到了段错误,但我只是迷路了。这是代码-

#include <iostream>
#include <fstream>
#include <sstream>
#include <list>

using namespace std;

typedef std::list<int> hSlots; //the list
typedef hSlots* hTable; //an array of lists

class HashTable
{
private:
int p; //p=number of slots in the hash table
hTable tmpPtr;
hTable *table;

 public:
HashTable(int p1);
int h1(int k);
~HashTable();

void chainedHashInsert(int x);

};

 HashTable::HashTable(int p1)
 {
p=p1;
hTable tTable[p];

//initializing to empty lists
for (int i=0; i<p; i++)
{
    tmpPtr = new hSlots;
    tTable[i] = tmpPtr;
}

table = tTable;
}

//destrcutor
HashTable::~HashTable()
{
delete table;
delete tmpPtr;
}

void HashTable::chainedHashInsert(int x)
{
tmpPtr = table[h1(x)];
cout<<"hashed"<<endl;
tmpPtr->push_front(x); //segmentation fault
}

int HashTable::h1(int k)
{
    int z = k%p;
    return z;
}

我没有使用很多列表,所以我不太确定

最佳答案

也许这毕竟是一个正确的答案。

您的问题是由于在 C++ 中手动进行内存管理(错误)而产生的,而实际上没有必要这样做。

这是我在 C++ 中使用直接自动内存管理的看法:

#include <vector>
#include <list>

using namespace std;

template <typename T, typename hSlots = std::list<T> >
class HashTable
{
private:
    int p; //p=number of slots in the hash table
    std::vector<hSlots> table;
    int getbucket(int k) { return k%p; }

public:
    HashTable(int p1) : p(p1), table(p1) {}

    void chainedHashInsert(int x)
    {
        auto& tmpPtr = table[getbucket(x)];
        tmpPtr.push_front(x);
    }
};

int main()
{
    HashTable<int> table(37);
}

关于c++ - Push_front 段错误 11 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15181552/

相关文章:

C++ RadixSort 高效方式

c++ - 使循环更快

c - 超出分配内存的指针访问不会导致段错误

c - 将缓冲区指针作为按值传递给函数时发生段错误,在该函数中该缓冲区发生重新分配

linux - 内核如何给出段。这样的场景有错吗?

c - 可变数组大小的段错误

c++ - 标准库算法对相邻元素之间的差异进行平均

c++ - 动态加载的 PIC 共享库具有来自 NPIC 依赖项的运行时未解析符号

C++ 继承和 valgrind 内存泄漏

C++ 段错误问题