0

I am getting error while inserting strings to memory. 0xC0000005 access violation error.I tried to change my array size which cause to bad allocation. int main part is only sending string words to insert function until file ends.

#include<string>
#include<iostream>
#include <fstream>
using namespace std;
const unsigned int MAX = INT16_MAX;
string *words = new string[MAX];
int* instances = new int[MAX];

//int* alloc = new int[MAX];
int ucounts = 0;

static unsigned int FNVHash(string str) {
const unsigned int fnv_prime = 0x811C9DC5;
unsigned int hash = 0;
unsigned int i = 0;
unsigned int len = str.length();

for (i = 0; i < len; i++)
{
    hash *= fnv_prime;
    hash ^= (str[i]);
}

return hash;
}

void insert(string input) {
//check first, add if not present

if (words[FNVHash(input)] != input) {  //<-Compiler shows error here.
    words[FNVHash(input)] = input;
    instances[FNVHash(input)]=1;
    ucounts++;
}
else {

    instances[FNVHash(input)]++;
}   
}
J.Sou
  • 1

1 Answers1

2

You don't have anything to limit the value returned by FNVHash to the range of indexes used by words. Either FNVHash needs to ensure the hash is within the range [0..NAX] or the user (insert) needs to do so.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • I could not fully understand.Can you explain bit more? – J.Sou Dec 27 '18 at 20:46
  • @J.Sou `FNVHash` returns an `unsigned int`, which appears to be at least a 32-bit number on your system. The `words` array only has `INT16_MAX` elements, which would be only 16 bits. Any number larger than 65535 would access out-of-bounds and likely cause the access violation. – 1201ProgramAlarm Dec 28 '18 at 01:34