Thursday, 8 August 2013

Memory access violation in objects vector

Memory access violation in objects vector

I am getting the following error while accessing the "put" method of the
HashMap class.
Unhandled exception at 0x00eece26 in abc.exe: 0xC0000005: Access violation
reading location 0xfeeefefe.
In the main function, I am creating a vector of HashMap objects. When I
try to call "put" method of the "HashMap" class, it gives the above
mentioned error. It works fine with single object but with the vector of
array it crashes. Any help? Thanks in advance.
I am using the following class definitions
class HashMap {
private:
int TABLE_SIZE;
LinkedHashEntry **table;
public:
HashMap(void){}
HashMap(int tableSize)
{
TABLE_SIZE = tableSize;
table = new LinkedHashEntry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
}
double get(int key)
{
int hash = (key % TABLE_SIZE);
if (table[hash] == NULL)
return -1;
else
{
LinkedHashEntry *entry = table[hash];
while (entry != NULL && entry->getKey() != key)
entry = entry->getNext();
if (entry == NULL)
return -1;
else
return entry->getValue();
}
}
void put(int key, double value)
{
int hash = (key % TABLE_SIZE);
if (table[hash] == NULL)
table[hash] = new LinkedHashEntry(key, value);
else
{
LinkedHashEntry *entry = table[hash];
while (entry->getNext() != NULL)
entry = entry->getNext();
if (entry->getKey() == key)
entry->setValue(value);
else
entry->setNext(new LinkedHashEntry(key, value));
}
}
...
};
The definition of LinkedHashEntry is as follows.
class LinkedHashEntry
{
private:
int key;
double value;
LinkedHashEntry *next;
public:
LinkedHashEntry(int key, double value) {
this->key = key;
this->value = value;
this->next = NULL;
}
int getKey() {
return key;
}
double getValue() {
return value;
}
void setValue(double value) {
this->value = value;
}
LinkedHashEntry *getNext() {
return next;
}
void setNext(LinkedHashEntry *next) {
this->next = next;
}
};
Here is the main method, where I am creating a vector array.
main()
{
...
// works fine here
HashMap *objTest = new HashMap(hashTableSize);
objTest ->put(1,1.1);
std::vector<HashMap> objHashTable(unprunedObjCount, HashMap(hashTableSize));
// crashes here
objHashTable[0].put(1, 1.1);
...
}

No comments:

Post a Comment