Search code examples
c++arraysfilecharstrcpy

Read access violation when attempting strcpy from file buffer to char array


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";
  }
}

Solution

  • 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