-1

I've been working on an assignment to implement hashing. In it, I read through a text file called "proteins". The problem occurs when I try to copy it to another char array. Visual Studio throws a read access violation.

#include <iostream>
#include <fstream>
using namespace std;
struct arrayelement {
  char protein[30];
  int count;
}; 
arrayelement proteins[40];
int main()
{
  char buffer[30];

  // open source file
  ifstream fin("proteins.txt");
  if (!fin) { cerr << "Input file could not be opened\n"; exit(1); }

  // loop through strings in file
  while (fin >> buffer) {
    int index = ((buffer[0] - 65) + (2 * (buffer[strlen(buffer)-1] - 65)) % 40);
    while (true)
    {
        if (proteins[index].protein == buffer)  // Found
        {
            proteins[index].count++;
            break;
        }
        if (proteins[index].protein[0] == 0)    // Empty
        {
            strcpy(proteins[index].protein, buffer); // <-- The error in question
            proteins[index].count++;
            break;
        }
        index++;                                // Collision
     }
  }

  // close file
  fin.close();


  for (int i = 0; i <= 40; i++)
  {
    cout << proteins[i].protein << "\t" << proteins[i].count << "\n";
  }
}
Noctimor
  • 3
  • 1

1 Answers1

2

If you get more than 30 chars here:

while (fin >> buffer) {

... or if index >= 40 here:

strcpy(proteins[index].protein, buffer);

... the program will probably crash (Undefined behavior). Also, these char*'s will not be pointing at the same address, so the comparison will fail:

proteins[index].protein == buffer
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Yep, it was the comparison that did me in. After rewriting it, everything runs. Part of the code here is given per the assignment -- the examples we're working with are guaranteed not to be above 30, and the index given is double what's needed, to practice collision resolution. Otherwise I'd absolutely clean that stuff up too. Thanks! – Noctimor Nov 13 '18 at 13:53
  • Great! Note: The index formula will result in 91 if the input string is `"z"`. It'll become: `index = 57 + 114 % 40` => `57 + (114 % 40)` – Ted Lyngmo Nov 13 '18 at 14:10