связанный список — ошибка шины c ++. Правильно работать с маленьким массивом, ошибка времени выполнения с большим массивом

Может кто-нибудь мне помочь? PrintAll (), listprintAll () и sizeLL () работают правильно, когда hashSize маленький, но не работает с большим числом, таким как число 9973.

printAll () и hashStats () оба являются методами в таблице классов, printALL () вызывает listprintAll () и hashStats () вызывает sizeLL () из другой структуры.

Все функции работают корректно с небольшим размером hashSize.

Извините за рис и запутался. впервые здесь .. Я использую MacBook, чтобы сделать эту работу.

В list.h

struct Node{

string key;
int value;

Node *next;

Node(const string &theKey, int theValue);

Node(const string &theKey, int theValue, Node *n);};

typedef Node * ListType;

В табл.ч

class Table {
public:

static const int HASH_SIZE = 9973;  // a prime number

// create an empty table, i.e., one where numEntries() is 0
// (Underlying hash table is HASH_SIZE.)
Table();

// create an empty table, i.e., one where numEntries() is 0
// such that the underlying hash table is hSize
Table(unsigned int hSize);

unsigned int hashSize;      // size of the hash table
ListType * data;           // (used in hashCode method above)
}

В list.cpp

void listprintAll(ListType list){

if(list ==NULL) {
cout << "[ ]" <<endl;
return;}
else{
Node * p=list;
while(p!= NULL){
cout << p->key << " " << p->value << ",";
p=p->next;
}
cout <<endl;
return;
}
}

int sizeLL(ListType list){

if(list ==NULL) {
return 0;}

else{
int count=0;
Node * p=list;

while(p!= NULL){
p=p->next;
count++;
}
return count;
}

В Table.cpp

Table::Table() {
hashSize=HASH_SIZE;
data = new ListType[hashSize];

}Table::Table(unsigned int hSize) {
hashSize=hSize;
data = new ListType[hashSize];

}void Table::printAll() const {

for(int i=0;i<hashSize;i++){
listprintAll(data[i]);
}
}

void Table::hashStats(ostream &out) const {

out << "number of buckets: "<< hashSize <<endl;
int number = numEntriesOfTable();
out << "number of entries: "<< number <<endl;

int countN0=0;
int longest=0;
int temp;

if(number!=0){
for(int i=0;i<hashSize;i++){
temp=sizeLL(data[i]);
if(temp!=0){
countN0++;
if(temp > longest){
longest=temp;
}
}
}
}
out << "number of non-empty buckets: "<< countN0 << endl;
out << "longest chain : "<< longest << endl;
}

1

Решение

Вы выделяете память для data в ваших конструкторах, но не инициализировать его. Это оставляет все ваши указатели с неопределенными значениями в них, которые могут быть 0 / NULL или может быть какое-то другое случайное значение указателя. Когда вы пытаетесь разыменовать их, вы получаете сбой.

Вы хотите обнулить выделенную память в конструкторе, используя цикл, memset, Или что-то вдоль этих линий.

1

Другие решения

Других решений пока нет …