Search code examples
c++linked-listhashtablebus-error

Bus error c++ Run correctly with small array, run time error with big array


Can anyone help me? The printAll(), listprintAll() and sizeLL() work correctly when hashSize is small but didn't work with big number, like number 9973.

printAll() and hashStats() are both method in Class Table, printALL() calls listprintAll() and hashStats() calls sizeLL() from another Structure.

All functions work correctly with give small hashSize.

Sorry about the pic and confused. first time here.. I'm using MacBook to do this work.

In 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;

In Table.h

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

In 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;
}

In 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;





}

Solution

  • You're allocating memory for data in your constructors but not initializing it. This leaves all your pointers with indeterminate values in them, which could be 0/NULL or could be some other random pointer value. When you try to dereference these you get the crash.

    You'll want to zero out your allocated memory in the constructor, using a loop, memset, or something along those lines.