For some reason, the value of the first element of the bucket array is being initialized to the size of the array, and growing in size after function calls.
Header file:
#ifndef TABLE
#define TABLE
#include <iostream>
#include <cstdlib>
typedef struct {
double successful , unsuccessful[2] ;
} Perform ;
using namespace std ;
template <class DATA>
class Table {
private :
DATA bucket[];
bool passbit[];
bool isFull[];
unsigned tableSize;
unsigned currentSize;
unsigned sProbes;
unsigned pbCount;
public :
explicit Table ( unsigned size = 5 ) ;
void clear ( ) ;
//bool insert ( DATA & data ) ;
bool insertD ( DATA & data ) ;
//bool fetch ( DATA & data ) const ;
bool getData ( unsigned i , DATA & data , bool & apassbit ) const ;
//Perform perform ( ) const ;
};
#endif
I’m only using the constructor and one function for now, but I will include everything.
#include <typeinfo>
#include <queue>
#include <iostream>
#include "table.hpp"
using namespace std ;
template <class DATA>
Table<DATA> :: Table ( unsigned size )
{
tableSize = size;
currentSize = 0;
sProbes = 0;
pbCount = 0;
bucket[tableSize];
cout << bucket[0] << "\n";
passbit[tableSize];
isFull[tableSize];
}
template <class DATA>
void Table<DATA> :: clear()
{
currentSize = 0;
sProbes = 0;
pbCount = 0;
for (int i = 0; i < tableSize; i++)
{
bucket[i] = 0;
passbit[i] = false;
isFull[i] = false;
}
}
template <class DATA>
bool Table<DATA> :: insertD ( DATA & data )
{
cout << bucket[0] << "\n";
unsigned value = unsigned ( data );
unsigned index = value % tableSize;
unsigned step = value % (tableSize - 2) + 1;
while ( isFull[index] && !(bucket[index] == data) )
{
passbit[index] = true;
pbCount++;
index -= step;
if ( index < 0 )
index += tableSize;
}
if ( isFull[index] && (bucket[index] == data) )
return false;
else
{
bucket[index] = data;
isFull[index] = true;
currentSize++;
return true;
}
}
template <class DATA>
bool Table<DATA> :: getData ( unsigned i , DATA & data , bool & apassbit ) const
{
if( bucket[i] != 0 )
{
data = bucket[i];
apassbit = passbit[i];
return true;
}
else
return false;
}
Main function:
#include <iostream>
#include "table.cpp"
#include "table.hpp"
int main()
{
Table<int> table = Table<int>();
int i = 1;
int ii = 2;
int iii = 3;
int iv = 4;
int v = 5;
table.insertD(i);
table.insertD(ii);
table.insertD(iii);
table.insertD(iv);
table.insertD(v);
return 0;
}
Output:
5
5
261
65797
16843013
Segmentation fault
The problem is that you are trying to initialize statically allocated arrays. You need to either use dynamically allocated arrays or declare your statically allocated arrays big enough to hold all the data you will need. Of course, since you are using c++, you should consider using STL vectors.
Here’s how you will need to adjust your code:
This uses dynamic allocation. Notice that you need to delete the array when a class instance is destructed.