Why am I getting "Exception Thrown: Write Access Violation" when I try running my C++ program on a Windows machine? [closed]

  access-violation, c++, io, oop, pointers

Premise:

I’m writing a program that will read from different text files in the same directory and make a makeshift "database" (arrays) of students from which I then conduct many operations such as comparing, printing info of students, etc.

Context:

First, it builds a faculty of all the engineering students from the various engineering discipline text files(ElCo, Mech, Civil) so it reads each line and populates arrays of Students (which is a class).
Then it does some very normal operations such as print out some general info on some of the students in this database.
It then reads the file student.txt and makes an array of all students across all disciplines and then conducts some very normal ops once again.

Problem:

My code compiles + runs perfectly and as expected with no warnings or errors on my Linux g++ compiler.

  • But if exported to a Windows machine, the code compiles but does not run due to the following: "Exception Thrown: Write Access Violation". I’m told that it may be due to a pointer issue on lines 47, 85, and 124 of the file facultyFunctions.cpp wherein I’m constructing Students and pushing them into the corresponding index in the pointer to an array, but I’m not sure.

  • It also fails to even compile on OSX machines throwing errors denoting improper use of const keywords, but that isn’t much of a worry for the time being.

My Steps:

Following these issues I’ve done the following:

  • Compiled on an impartial online IDE + compiler such as Repl.it and it works just as perfectly as on my machine (yes, a very amateur step to error-checking but I had to check that my machine wasn’t the problem here)

  • Intensive Debugging: I’ve spent close to an hour setting breakpoints almost everywhere and stepping thru as well as into every single line of code that I’ve written, and though I’m not an expert I couldn’t spot anything out of place, everything was working as expected.

  • Browsing through every single "Write Access Violation error" question on Stack Overflow to no avail.

Here is my code:

There are 9 files in all (4 text files containing student info (separated by spaces and each student on a different line) / 2 library files / 2 cpp files that elaborate the initialization of the classes and functions in the library files / 1 main cpp file)

  1. Main file (main.cpp):
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include <fstream>
#include "student.h"
#include "faculty.h"
using namespace std;

int main(int argc, char ** argv)
{
  //Create Faculty Object
  Faculty Engineering;
  cout << "Created Faculty object: Engineering!" <<endl;
  cout <<endl;
  string elco = "ElCo";
  string mech = "Mech";
  string civil = "Civil";

  //Test member functions 1
  cout << "Testing highest GPA in each faculty..." <<endl;
  cout <<endl;
  Engineering.Highest_GPA(elco);
  cout <<endl;
  Engineering.Highest_GPA(mech);
  cout <<endl;
  Engineering.Highest_GPA(civil);
  cout <<endl;

  //Test member functions 2
  cout <<endl;
  cout << "Counting number of Undergrads in Engineering..." <<endl;
  cout <<endl;
  cout << "There are " << Engineering.N_of_Undergrad(elco) << " Undergrads in Electrical and Computer Engineering." <<endl;
  cout << "There are " << Engineering.N_of_Undergrad(mech) << " Undergrads in Mechanical Engineering." <<endl;
  cout << "There are " << Engineering.N_of_Undergrad(civil) << " Undergrads in Civil Engineering." <<endl;
  cout << "There are " << Engineering.N_of_Undergrad(elco) + Engineering.N_of_Undergrad(mech) + Engineering.N_of_Undergrad(civil) << " Undergrads in total in Engineering." <<endl;
  cout <<endl;
  //Test member functions 3
  cout <<endl;
  cout << "Counting number of Grads in Engineering..." <<endl;
  cout <<endl;
  cout << "There are " << Engineering.N_of_Grad(elco) << " Grads in Electrical and Computer Engineering." <<endl;
  cout << "There are " << Engineering.N_of_Grad(mech) << " Grads in Mechanical Engineering." <<endl;
  cout << "There are " << Engineering.N_of_Grad(civil) << " Grads in Civil Engineering." <<endl;
  cout << "There are " << Engineering.N_of_Grad(elco) + Engineering.N_of_Grad(mech) + Engineering.N_of_Grad(civil) << " Grads in total in Engineering." <<endl;
  cout <<endl;
  //Test member functions 4
  cout <<endl;
  cout << "Computing average GPA of Undergrads in each Department..." <<endl;
  cout <<endl;
  cout << "The GPA average of Electrical and Computer Engineering Undergrads is: " << Engineering.Avg_Undergrad(elco) <<endl;
  cout << "The GPA average of Mechanical Engineering Undergrads is: " << Engineering.Avg_Undergrad(mech) <<endl;
  cout << "The GPA average of Civil Engineering Undergrads is: " << Engineering.Avg_Undergrad(civil) <<endl;
  cout <<endl;
  //Test member functions 5
  cout <<endl;
  cout << "Computing average GPA of Grads in each Department..." <<endl;
  cout <<endl;
  cout << "The GPA average of Electrical and Computer Engineering Grads is: " << Engineering.Avg_Grad(elco) <<endl;
  cout << "The GPA average of Mechanical Engineering Grads is: " << Engineering.Avg_Grad(mech) <<endl;
  cout << "The GPA average of Civil Engineering Grads is: " << Engineering.Avg_Grad(civil) <<endl;
  cout <<endl;
  cout <<endl;

  //Read, Parse and populate all available student objects
  ifstream file;
  file.open("students.txt");
  cout << "Opening file: students.txt..." <<endl;
  if(!file)
  {
    cout << "Error opening file! Terminating processes now, Exit code 1" <<endl;
    exit(1);
  }
  string line, fname, lname, id, dob, gpa, syr, cred, prog;
  int num = 0;
  Student* arrStudents = nullptr;
  if(file.is_open())
  {
    cout << "Successfully opened students.txt!" <<endl;
    cout << "Populating Students..."<<endl;
    cout <<endl;
    int i = 0;
    while(getline(file, line))
    {
      if (num == 0)
      {
        num = stoi(line);
        arrStudents = new Student[num];
      }
      else
      {
        istringstream iss(line);
        getline(iss, fname, ' ');
        getline(iss, lname, ' ');
        getline(iss, id, ' ');
        getline(iss, dob, ' ');
        getline(iss, gpa, ' ');
        getline(iss, syr, ' ');
        getline(iss, cred, ' ');
        getline(iss, prog, ' ');
        arrStudents[i] = Student(fname, lname, id, dob, gpa, syr, cred, prog);
        cout << "Successfully populated Student " << i+1 << " out of " << num <<endl;
        ++i;
      }
    }
  }
  cout << "Successfully populated all Students!" <<endl;
  cout <<endl;
  cout <<endl;

  string userid;
  cout << "Please input the ID of a student whom you want to see their entire info: ";
  cin >> userid;
  cout <<endl;
  int index = -1;
  for(int i = 0; i < num; ++i)
  {
    if(arrStudents[i].getID() == userid) index = i;
  }
  if(index == -1)
  {
    cout << "Wrong ID entered, exiting program now, exit code 1" <<endl;
    exit(1);
  }

  arrStudents[index].Print_Std_Info();
  if(arrStudents[index].CompleteProgram())
  {
    cout << "Their program has been completed!" <<endl;
  }
  else
  {
    cout << "Their program has not been completed yet!" <<endl;
  }

  cout << "Grade: " << arrStudents[index].StudentStatus() <<endl;
  cout <<endl;
  string compid, idcomp;
  cout << "Please enter the ID of 2 students who's GPAs you wish to compare (each on a separate newline): " <<endl;
  cin >> compid;
  cin >> idcomp;
  cout <<endl;
  index = -1;
  int dexin = -1;
  for(int i = 0; i < num; ++i)
  {
    if(arrStudents[i].getID() == compid) index = i;
  }
  if(index == -1)
  {
    cout << "Wrong ID entered, Exiting program now, Exit code 1" <<endl;
    exit(1);
  }
  for(int i = 0; i < num; ++i)
  {
    if(arrStudents[i].getID() == idcomp) dexin = i;
  }
  if(dexin == -1)
  {
    cout << "Wrong ID entered, Exiting program now, Exit code 1" <<endl;
    exit(1);
  }
  string betterid = arrStudents[index].CompareGPA(arrStudents[dexin]);
  cout << "Here is the ID of the student with the better GPA: " << betterid <<endl;

  cout <<endl;
  cout <<endl;
  cout << "Successfully reached the end of program!" <<endl;
  cout << "Exiting with exit code 0" <<endl;



  return 0;
}

  1. First Library file (students.h) defining the student class, attributes, and member functions:
#ifndef STUDENT_H
#define STUDENT_H

#include <iostream>
#include <string>
using namespace std;

class Student
{

private:
// students' attribs
    string m_firstName;
    string m_lastName;
    string m_id;
    string m_dateBirth;
    float m_gpa;
    int m_startYear;
    int m_completedCredit;
    string m_program;

public:
  Student() = default; //Default Constructor (unused)
  ~Student() = default; //Destructor (set to compiler default)
  Student(const Student& source); //Copy constructor
  Student& operator = (const Student& source); //Copy Assignment Operator
  Student(string&, string&, string&, string&, string&, string&, string&, string&); //Constructor to populate object

  //Get functions: constant methods returning constants
  //Set funcs: const methods passing values to attributes
  const string& getFirstName() const;
  void setFirstName(string&);
  const string& getLastName() const;
  void setLastName(string&);
  const string& getID() const;
  void setID(string&);
  const string& getBirth() const;
  void setBirth(string&);
  const float& getGPA() const;
  void setGPA(string&);
  const int& getStartYear() const;
  void setStartYear(string&);
  const int& getCompletedCredit() const;
  void setCompletedCredit(string&);
  const string& getProgram() const;
  void setProgram(string&);

  //Additional member functions
  const bool CompleteProgram() const;
  const string StudentStatus()const;
  void Print_Std_Info();
  //Compare function
  const string& CompareGPA(const Student& source) const;
};
#endif

  1. Second library file (faculty.h) defining the Faculty class, attribs, and member funcs:
#ifndef FACULTY_H
#define FACULTY_H

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "student.h"

using namespace std;

class Faculty
{

private:
  Student* m_ElCoStudents;
  Student* m_MechStudents;
  Student* m_CivStudents;
  int m_numMechStudents;
  int m_numElCoStudents;
  int m_numCivStudents;

public:
  Faculty();
  ~Faculty();


  void Highest_GPA(string dept);
  const int N_of_Undergrad(string dept);
  const int N_of_Grad(string dept);
  const float Avg_Undergrad(string dept);
  const float Avg_Grad(string dept);
};

#endif

  1. Implementation of Student class (studentFunctions.cpp):
#include "student.h"
#include <iostream>
#include <string>
using namespace std;



Student::Student(const Student& source)
{
  this->m_firstName = source.m_firstName;
  this->m_lastName = source.m_lastName;
  this->m_id = source.m_id;
  this->m_dateBirth = source.m_dateBirth;
  this->m_gpa = source.m_gpa;
  this->m_startYear = source.m_startYear;
  this->m_completedCredit = source.m_completedCredit;
  this->m_program = source.m_program;
}

Student& Student::operator = (const Student& source)
{
  this->m_firstName = source.m_firstName;
  this->m_lastName = source.m_lastName;
  this->m_id = source.m_id;
  this->m_dateBirth = source.m_dateBirth;
  this->m_gpa = source.m_gpa;
  this->m_startYear = source.m_startYear;
  this->m_completedCredit = source.m_completedCredit;
  this->m_program = source.m_program;
  return *this;
}

Student::Student(string& firstName,
                 string& lastName,
                 string& id,
                 string& dateBirth,
                 string& gpa,
                 string& startYear,
                 string& completedCredit,
                 string& program)
{
  setFirstName(firstName);
  setLastName(lastName);
  setID(id);
  setBirth(dateBirth);
  setGPA(gpa);
  setStartYear(startYear);
  setCompletedCredit(completedCredit);
  setProgram(program);
}



// get funcs
const string& Student::getFirstName() const
{
  return this->m_firstName;
}
void Student::setFirstName(string& fname)
{
  this->m_firstName = fname;
}

const string& Student::getLastName() const
{
  return this->m_lastName;
}
void Student::setLastName(string& lname)
{
  this->m_lastName = lname;
}

const string& Student::getID() const
{
    return this->m_id;
}
void Student::setID(string& id)
{
  this->m_id = id;
}

const string& Student::getBirth() const
{
    return this->m_dateBirth;
}
void Student::setBirth(string& birth)
{
  this->m_dateBirth = birth;
}

const float& Student::getGPA() const
{
  return this->m_gpa;
}
void Student::setGPA(string& gpa)
{
  this->m_gpa = stof(gpa);
}

const int& Student::getStartYear() const
{
  return this->m_startYear;
}
void Student::setStartYear(string& syr)
{
  this->m_startYear = stoi(syr);
}

const int& Student::getCompletedCredit() const
{
  return this->m_completedCredit;
}
void Student::setCompletedCredit(string& cred)
{
  this->m_completedCredit = stoi(cred);
}

const string& Student::getProgram() const
{
  return this->m_program;
}
void Student::setProgram(string& prog) 
{
  this->m_program = prog;
}



// function for completed credits. If program is finished or not
const bool Student::CompleteProgram() const
{
    // bachelor degree
  if(this->m_program == "B")
    // to complete program, must complete at least 140 credits
    return this->m_completedCredit >= 140;

    // masters degree
  else if(this->m_program == "M")
    // to complete program, must complete at least 16 credits
    return this->m_completedCredit >= 16;

    //PhD degree
  else if(this->m_program == "P")
    // to complete program, must complete at least 12 credits
    return this->m_completedCredit >= 12;

    // if another progrem is entered, user error
  else
    return false;
}


// function that translates gpa to letter grade
const string Student::StudentStatus() const
{
  if(this->m_gpa >= 3.5)
    return "A+";

  else if(this->m_gpa >= 3)
    return "A";

  else if(this->m_gpa >= 2.5)
    return "B";

  else if(this->m_gpa >= 2)
    return "C";

  else
    return "D";
}


// function that prints out all student attributes
void Student::Print_Std_Info()
{
  cout << "First name: " << this->m_firstName <<endl;
  cout << "Last name: " << this->m_lastName <<endl;
  cout << "Student ID: " << this->m_id <<endl;
  cout << "Date of Birth: " << this->m_dateBirth <<endl;
  cout << "GPA: " << this->m_gpa <<endl;
  cout << "Start year: " << this->m_startYear <<endl;
  cout << "Completed credit: " << this->m_completedCredit <<endl;
  cout << "Program: ";

  if(this->m_program == "B")
    cout<<"Bachelor" <<endl;

  else if(this->m_program == "M")
    cout<<"Master's" <<endl;

  else if(this->m_program == "P")
    cout<<"Ph.D" <<endl;

  else
    cout << this->m_program <<endl;
}


// function compares gpa of two students. Return id of the student with higher gpa
const string& Student::CompareGPA(const Student& source) const
{

  // student's gpa is higher or equal to student1's gpa, their id will be returned
  if(this->m_gpa >= source.getGPA())
    return this->m_id;

  // if not, return id of the student of student1
  else
    return source.getID();
}

  1. Implementation of Faculty class (facultyFunctions.cpp):
#include "student.h"
#include "faculty.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <bits/stdc++.h>
#include <sstream>
using namespace std;

Faculty::Faculty()
{

  ifstream file; //initialized a reading file
  //Declared all variables of the scope
  this->m_ElCoStudents = nullptr;
  string line, fname, lname, id, dob, gpa, syr, cred, prog;
  int num = 0;
  file.open("student_elec_comp.txt");
  if(!file)
  {
    cout << "Error opening file! Terminating processes now, exit code 1" <<endl;
    exit(1);
  }
  if(file.is_open())
  {
    int i = 0;
    while(getline(file, line))
    {
      if (num == 0)
      {
        num = stoi(line);
        this->m_numElCoStudents = num;
        this->m_ElCoStudents = new Student[num];
      }
      else
      {
        istringstream iss(line);
        getline(iss, fname, ' ');
        getline(iss, lname, ' ');
        getline(iss, id, ' ');
        getline(iss, dob, ' ');
        getline(iss, gpa, ' ');
        getline(iss, syr, ' ');
        getline(iss, cred, ' ');
        getline(iss, prog, ' ');
        this->m_ElCoStudents[i] = Student(fname, lname, id, dob, gpa, syr, cred, prog);
        ++i;
      }
    }
  }
  file.close();


  this->m_MechStudents = nullptr;
  num = 0;
  file.open("student_mech.txt");
  if(!file)
  {
    cout << "Error opening file! Terminating processes now, exit code 1" <<endl;
    exit(1);
  }
  if(file.is_open())
  {
    int i = 0;
    while(getline(file, line))
    {
      if (num == 0)
      {
        num = stoi(line);
        this->m_numMechStudents = num;
        this->m_MechStudents = new Student[num];
      }
      else
      {
        istringstream iss(line);
        getline(iss, fname, ' ');
        getline(iss, lname, ' ');
        getline(iss, id, ' ');
        getline(iss, dob, ' ');
        getline(iss, gpa, ' ');
        getline(iss, syr, ' ');
        getline(iss, cred, ' ');
        getline(iss, prog, ' ');
        this->m_MechStudents[i] = Student(fname, lname, id, dob, gpa, syr, cred, prog);
        ++i;

      }
    }
  }
  file.close();


  this->m_CivStudents = nullptr;
  num = 0;
  file.open("student_civil.txt");
  if(!file)
  {
    cout << "Error opening file! Terminating processes now, exit code 1" <<endl;
    exit(1);
  }
  if(file.is_open())
  {
    int i = 0;
    while(getline(file, line))
    {
      if (num == 0)
      {
        num = stoi(line);
        this->m_numCivStudents = num;
        this->m_CivStudents = new Student[num];
      }
      else
      {
        istringstream iss(line);
        getline(iss, fname, ' ');
        getline(iss, lname, ' ');
        getline(iss, id, ' ');
        getline(iss, dob, ' ');
        getline(iss, gpa, ' ');
        getline(iss, syr, ' ');
        getline(iss, cred, ' ');
        getline(iss, prog, ' ');
        this->m_CivStudents[i] = Student(fname, lname, id, dob, gpa, syr, cred, prog);
        ++i;
      }
    }
  }
  file.close();
}

Faculty::~Faculty()
{
  delete[] m_ElCoStudents;
  delete[] m_MechStudents;
  delete[] m_CivStudents;
}

void Faculty::Highest_GPA(string dept)
{
  float high = 0.0;
  int index;
  if(dept == "ElCo")
  {
    for(int ctr = 0; ctr < this->m_numElCoStudents; ++ctr)
    {
      if(this->m_ElCoStudents[ctr].getGPA() > high)
      {
        high = this->m_ElCoStudents[ctr].getGPA();
        index = ctr;
      }
    }

    cout << "The highest GPA in Electrical and Computer Engineering is: " << high << "nThis is their info: "<<endl;
    this->m_ElCoStudents[index].Print_Std_Info();
  }
  else if(dept == "Mech")
  {
    for(int ctr = 0; ctr < this->m_numMechStudents; ++ctr)
    {
      if(this->m_MechStudents[ctr].getGPA() > high)
      {
        high = this->m_MechStudents[ctr].getGPA();
        index = ctr;
      }
    }
    cout << "The highest GPA in Mechanical Engineering is: " << high << "nThis is their info: "<<endl;
    this->m_MechStudents[index].Print_Std_Info();
  }
  else if(dept == "Civil")
  {
    for(int ctr = 0; ctr < this->m_numCivStudents; ++ctr)
    {
      if(this->m_CivStudents[ctr].getGPA() > high)
      {
        high = this->m_CivStudents[ctr].getGPA();
        index = ctr;
      }
    }
    cout << "The highest GPA in Civil Engineering is: " << high << "nThis is their info: "<<endl;
    this->m_CivStudents[index].Print_Std_Info();
  }
}

const int Faculty::N_of_Undergrad(string dept)
{
  int ugrad = 0;
  if(dept == "ElCo")
  {
    for(int ctr = 0; ctr < m_numElCoStudents; ++ctr)
    {
      if(m_ElCoStudents[ctr].getProgram() == "B") ++ugrad;
    }
  }
  else if(dept == "Mech")
  {
    for(int ctr = 0; ctr < m_numMechStudents; ++ctr)
    {
      if(m_MechStudents[ctr].getProgram() == "B") ++ugrad;
    }
  }
  else if(dept == "Civil")
  {
    for(int ctr = 0; ctr < m_numCivStudents; ++ctr)
    {
      if(m_CivStudents[ctr].getProgram() == "B") ++ugrad;
    }
  }
  return ugrad;
}


const int Faculty::N_of_Grad(string dept)
{
  int grad = 0;
  if(dept == "ElCo")
  {
    for(int ctr = 0; ctr < m_numElCoStudents; ++ctr)
    {
      if(m_ElCoStudents[ctr].getProgram() != "B") ++grad;
    }
  }
  else if(dept == "Mech")
  {
    for(int ctr = 0; ctr < m_numMechStudents; ++ctr)
    {
      if(m_MechStudents[ctr].getProgram() != "B") ++grad;
    }
  }
  else if(dept == "Civil")
  {
    for(int ctr = 0; ctr < m_numCivStudents; ++ctr)
    {
      if(m_CivStudents[ctr].getProgram() != "B") ++grad;
    }
  }
  return grad;
}

const float Faculty::Avg_Undergrad(string dept)
{
  float avg = 0.0;
  float ret = 0.0;
  if(dept == "ElCo")
  {
    for(int ctr = 0; ctr < m_numElCoStudents; ++ctr)
    {
      if(m_ElCoStudents[ctr].getProgram() == "B") avg += m_ElCoStudents[ctr].getGPA();
    }
    string elco = "ElCo";
    int num = Faculty::N_of_Undergrad(elco);
    if(num == 1) return avg;
    ret = avg / num;
  }
  else if(dept == "Mech")
  {
    for(int ctr = 0; ctr < m_numMechStudents; ++ctr)
    {
      if(m_MechStudents[ctr].getProgram() == "B") avg += m_MechStudents[ctr].getGPA();
    }
    string mech = "Mech";
    int num = Faculty::N_of_Undergrad(mech);
    if(num == 1) return avg;
    ret = avg / num;
  }
  else if(dept == "Civil")
  {
    for(int ctr = 0; ctr < m_numCivStudents; ++ctr)
    {
      if(m_CivStudents[ctr].getProgram() == "B") avg += m_CivStudents[ctr].getGPA();
    }
    string civil = "Civil";
    int num = Faculty::N_of_Undergrad(civil);
    if(num == 1) return avg;
    ret = avg / num;
  }
  return ret;
}


const float Faculty::Avg_Grad(string dept)
{
  float avg = 0.0;
  float ret = 0.0;
  if(dept == "ElCo")
  {
    for(int ctr = 0; ctr < m_numElCoStudents; ++ctr)
    {
      if(m_ElCoStudents[ctr].getProgram() != "B") avg += m_ElCoStudents[ctr].getGPA();
    }
    string elco = "ElCo";
    int num = Faculty::N_of_Grad(elco);
    if(num == 1) return avg;
    ret = avg / num;
  }
  else if(dept == "Mech")
  {
    for(int ctr = 0; ctr < m_numMechStudents; ++ctr)
    {
      if(m_MechStudents[ctr].getProgram() != "B") avg += m_MechStudents[ctr].getGPA();
    }
    string mech = "Mech";
    int num = Faculty::N_of_Grad(mech);
    if(num == 1) return avg;
    ret = avg / num;
  }
  else if(dept == "Civil")
  {
    for(int ctr = 0; ctr < m_numCivStudents; ++ctr)
    {
      if(m_CivStudents[ctr].getProgram() != "B") avg += m_CivStudents[ctr].getGPA();
    }
    string civil = "Civil";
    int num = Faculty::N_of_Grad(civil);
    if(num == 1) return avg;
    ret = avg / num;
  }
  return ret;
}

Anyone who has any suggestions, answers, solutions, anything at all to solve my query and/or optimize my code is welcome, no contribution is too small!

Thank you all very much in advance!

Source: Windows Questions C++

LEAVE A COMMENT