Underflow error reading the file

I was wondering what is wrong with my code since it giving me a segmentation fault and I'm not sure if the problem is in how the file is being accessed or being read into the file. I'm supposed to read the file in through the command line and make sure only one file is permitted to be read. I am receiving the following error every time I try to run the program:

terminate called after throwing an instance of 'std::ios_base::failure'
what(): basic_filebuf::underflow error reading the file
Segmentation fault

I will post a portion of my code where I think the problem might be occurring.


#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

struct userRole{
char *user;
char *role;
};


int main(int argc, char *argv[])
{
bool run = true;
bool propA = true;
bool propB = true;
bool propC = true;
ifstream inFile;
userRole array;
char inUser;
char inRole;
int count = 0;
array.user = new char[count];
array.role = new char[count];
string fileName = *argv;

// display error message
if(argc > 2){
run = false;
cout << endl << endl
<< "Cannot accept more than two commands. "
<< "Please abort the program." << endl << endl << endl;
}

if(run){
// read in elements of file
inFile.open(fileName.c_str());

// error check
if (inFile.fail()){
cout << endl;
cout << "Problem with the file... press Enter to exit the program... ";
cin.get();
cout << endl << endl;
return 0;
}

while (inFile >> inUser){
inFile >> inRole;
array.user[count] = inUser;
array.role[count] = inRole;
count++;
}

inFile.close();

string users = array.user;
string roles = array.role;

}

return 0;
}

Any advice on how to fix this problem would be greatly appreciated.
1
2
3
4
5
6
7
8
int count = 0;  // count is zero
array.user = new char[count];  // so you are allocating an array of size 0.  IE: nothing
array.role = new char[count];  // these lines are worthless.

//...

array.user[count] = inUser;  // trying to write to array.user, but array.user is not large 
   // enough to hold any data.  **memory corruption** 




Do yourself a favor: ditch the char* nonsense and just use strings.
Topic archived. No new replies allowed.