push_front segmentation fault 11 c ++

时间:2013-03-03 01:43:29

标签: 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;
}

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

3 个答案:

答案 0 :(得分:2)

毕竟,这可能是一个正确的答案。

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

答案 1 :(得分:0)

因为tTableHashTable的局部变量,所以当HashTable方法返回时它会消失,并将table作为悬空指针。 所以要摆脱这样做,如下所示;使用new为表创建一个空间。

HashTable::HashTable(int p1)
 {
p=p1;
table  = new ttTable[p];

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

答案 2 :(得分:0)

table = tTable;

这一行是问题(或至少其中一个)。

您将指向自动对象的指针存储到成员变量中,然后在对象被销毁后解除引用(并删除!)它。