Okay well I'm not to advanced at C++, its only my 2 quarter in college taking Computer Science so please don't say anything that will go straight over my head haha. Well the code I have compiles just fine but when I got to run it I'm getting this seg fault error and I'm pretty sure it has something to do with the pointers in my code, if someone could just look at it and help me out id appropriate it. Thanks
So what this code is trying to do is read a .dat file that has 3 columns the first two are numbers that represent cities and the third is the cost of a cable that is connected between them. It will read the file and then find the cheapest cost that has all cities connected some way or form.
My Code:
You does not init you class members, the core position is "Cable **cables = new Cable*[ncables];", because ncables not init. you construct function Solver() should init all members. like this :
First, let me say that this class is a horrible mess and needs to be completely redesigned.
That said, if you declare a variable in a member function of a class that has the same name as a class variable, you hide the class variable. It looks like you think doing this is the way to access the class variable. It is not.
//reads the file from main
void readFile(char **argv) {
fstream *fin = new fstream(argv[1], ios::in);
if (fin->fail()) {
cerr << "Cannot open file " << argv[1] << "\n";
exit(0);
}
while (getline(*fin, buffer)) ncables++;
fin->close();
fin->clear();
Cable **cables = new Cable*[ncables];
int sum = 0;
fin->open(argv[1], ios::in);
for (int i = 0; i < ncables; i++) {
cables[i] = new Cable();
*fin >> cables[i]->city1>> cables[i]->city2 >> cables[i]->cost;
sum += cables[i]->cost;
}
fin->close();
fin->clear();
}
I suspect you should be manipulating the cables variable that is a part of the class, not a local variable with the same name. When the function returns, the local cables is discarded and you have a nice memory leak. Also, there's no reason to use new for your fstream here (especially as you don't release the memory you allocate.) This should probably look like:
//reads the file from main
void readFile(char **argv) {
ifstream fin(argv[1]);
if (fin.fail()) {
cerr << "Cannot open file " << argv[1] << "\n";
exit(0);
}
while (getline(fin, buffer)) ncables++;
fin.close();
fin.clear();
cables = new Cable*[ncables];
sum = 0;
fin.open(argv[1]);
for (int i = 0; i < ncables; i++) {
cables[i] = new Cable();
fin >> cables[i]->city1>> cables[i]->city2 >> cables[i]->cost;
sum += cables[i]->cost;
}
}
And of course you need to make similar changes in all of your member functions, but before you do that consider chucking the entire design, because it sucks. =)