Вызвано исключение по адресу 0x00007FF7C52DF005 в Practice2.exe: 0xC0000005: нарушение прав доступа при чтении по адресу 0xFFFFFFFFFFFFFFFF

Не могу понять, почему программа странно работает: иногда отрабатывает корректно, а иногда просто выдает ошибку. Задание такое - необходимо создать бинарный файл с записями(слово<ключ> и кол-во вхождений этого слова в текст) и хеш-таблицу для удобного поиска слова по бинарному файлу. Долго пытался понять в чем проблема, так и не понял. Надеюсь на вашу помощь.

main

#include <iostream>
#include<fstream>
#include< stdlib.h>
#include <time.h>
#include<vector>
#include<string>
#include <cstdio>

using namespace std;
int main()
{ 
   srand(time(0));
   int menu;
   int i;
   cout << "Введите количество записей в файле\n-->";
   cin >> i;
   fill_file(i);
   hash_table hashtable(27);
   string record = "";
   i = 0;
   ifstream offile("test1.bin", ios::binary);
   while (offile.read((char*)&record, sizeof(string))) {
       hashtable.insert_key(i, record.substr(0, 10));
       i++;
   }
   offile.close();
   cout << "----------------" << endl;
   cout << "Таблица создана" << endl;
   cout << "----------------" << endl;
   string word;
   cout << "\nВведите слово для поиска\n-->";
   cin >> word;
   hashtable.find_key(word);
}

class hash_table

class hash_table {
private: 
    vector <node*> htable;
    int size;

public:
    hash_table(int size);
    int hashf(string word); // хеш-функция
    void insert_key(int i, string word); // добавить запись в хеш-таблтицу
    void del_key(string word); // удалить запись из таблицы
    void find_key(string word); // найти ключ в таблице
};

hash_table::hash_table(int size)
{
    this->size = size;
    vector <node*> temptable(size);
    htable = temptable;
}

int hash_table::hashf(string word)
{
    return int(word[0]) % 97;
}

void hash_table::insert_key(int i, string word)
{
    node* nd = new node();
    nd->key = i;
    if (!htable.at(makehash(word))) {
        htable.at(makehash(word)) = nd;
    }
    else {
        node* pointer = htable.at(makehash(word));
        while (pointer->point) {
            pointer = pointer->point;
        }
        pointer->point = nd;
    }
}

void hash_table::find_key(string word)
{
    string temp = "";
    if (htable.at(makehash(word))) {
        ifstream ofile("test1.bin", ios::binary);
        ofile.clear();
        ofile.seekg(sizeof(int) * htable.at(makehash(word))->key, ofile.beg);
        ofile.read((char*)&temp, sizeof(string));
        if (temp.substr(0, word.length()) == word) { cout << "Ваше слово встречается " << temp.substr(word.length() + 1, temp.length()) << " раз" << endl; }
        else if (temp.substr(0, word.length()) != word) {
            ofile.close();
            node* nd = htable.at(hashf(word));
            while (temp.substr(0, word.length()) != word) {
                ifstream ofile("test1.bin", ios::binary);
                nd = nd->point;
                ofile.clear();
                ofile.seekg(sizeof(string) * nd->key, ofile.beg);
                ofile.read((char*)&temp, sizeof(string));
                ofile.close();
            }
            cout << "Ваше слово встречается " << temp.substr(word.length() + 1, temp.length()) << " раз" << endl;
        }
        

    }
}


void fill_file(int i) {
    vector<string> words;
    int entr_number;
    string word = "";
    string record = "";
    for (int j = 0; j < i; j++) {
        word = "";
        for (int k = 0; k < 10; k++) {
            word += char(97 + rand() % 26);
        }
        words.push_back(word);
    }
    ofstream infile("test1.bin", ios::binary);
    for (int i = 0; i < words.size(); i++) {
        entr_number = 10 + rand() % 80;
        record = words.at(i) + ' ' + to_string(entr_number);
        infile.write((char*)&record, sizeof(string));
        cout << words.at(i) << " встречается " << entr_number << " раз" << endl;
    }
    infile.close();
}

struct node

struct node {
    int key = 0; // ключ
    node* point = NULL; //указатель на след элемент в цепочке
};

Ответы (1 шт):

Автор решения: TheRyuTeam

Попробуйте воспользоваться дебаггером, скорее всего ошибка в том, что где-то есть разыменовывание NULL указателя.

record.data() ???

while (offile.read((char*)&record, sizeof(string))) {
    hashtable.insert_key(i, record.substr(0, 10));
    i++;
}

Так же есть вопросы к

int hash_table::hashf(string word)
{
    return int(word[0]) % 97;
}

Что если длинна слова == 0? Еще если эта функция вернет значение больше размера вектора, то

node* nd = htable.at(hashf(word));

бросит исключение

Попробуйте внимательнее посмотреть на все элементы, взятые из вектора.

→ Ссылка