所以我有这个程序,它运行并做它想做的事情。但是在执行结束时它会引发分段错误。我运行调试器,它说:"程序收到信号SIGSEGV,分段错误"。我逐行运行调试器,它似乎在完成所有操作后将错误抛出到main函数中。
代码:
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
using namespace std;
const int MAX = 100;
int firstDigit = 0; //vertex number
int verticesCount = 0;
int adjVerticesCount = 0;
class graph
{
private:
int n;
int data[MAX];
int gptr[MAX][MAX];
public:
void create();
void cleanupMatrix();
void topological();
};
void graph::create()
{
cleanupMatrix(); // initialize the adj matrix with zeros
ifstream infile ("input.txt");
string line, line_separated;
if (infile.is_open())
{
while (infile.good())
{
while(getline(infile,line)) //reads a line
{
if(line.length() == 0)
{
n = verticesCount;
topological();
verticesCount = 0;
continue;
}
istringstream iss(line);
while(getline(iss, line_separated, ' ')) //separate numbers in each line read
{
//convert string digit to int digit
int temp;
temp = atoi(line_separated.c_str());
if(firstDigit == 0) //On each line the first digit is the vertex. The rest is the adjacency vertices
{
firstDigit = temp;
verticesCount++;
data[firstDigit] = firstDigit;
}
else
{ //pointing the g array to linked list containing adjacency vertices
adjVerticesCount++;
gptr[firstDigit][temp] = 1;
}
}
adjVerticesCount = 0;
firstDigit = 0;
}
n = verticesCount;
topological();
verticesCount = 0;
}
infile.close();
}
else
{
cout << "Error: Could not open file 'input.txt'" << endl; //oopsi.. where is the file?
}
}
void graph::cleanupMatrix()
{
int x,y;
for(x=1;x<=MAX;x++)
for(y=1;y<=MAX;y++)
gptr[x][y] = 0;
}
void graph::topological()
{
int flag;
int i,j;
int poset[MAX],included[MAX];
for(i=1;i<=n;i++)
{
poset[i]=0;
included[i]=false;
}
int k = 1;
flag = true;
int zeroindegree;
int c = 1;
while(flag==1)
{
for(i=1;i<=n;i++)
{
if(!included[i])
{
zeroindegree=true;
for(j=1;j<=n;j++)
{
if(gptr[j][i]>0)
{
zeroindegree=false;
break;
}
}
if(zeroindegree)
{
included[i]=true;
poset[k]=data[i];
k=k+1;
for(j=1;j<=n;j++)
{
gptr[i][j]=-1;
gptr[j][i]=-1;
}
break;
}
}
}
if(i==n+1)
{
if(zeroindegree==false)
{
cout<<"Graph is not acyclic\n";
return;
}
else
{
poset[k]=data[i-1];
k=k+1;
flag=false;
}
}
}
ofstream outFile;
outFile.open("output.txt", ios_base::app);
cout << "Topological sorting:\n";
outFile << "Topological sorting:\n";
for(i=1;i<=n;i++)
{
cout << poset[i];
outFile << poset[i];
if(i != n)
{
cout << ", ";
outFile << ", ";
}
}
cout << "\n" << endl;
outFile << "\n" << endl;
outFile.close();
cleanupMatrix();
}
int main()
{
//Clear the output file
fstream file;
file.open("output.txt", fstream::out | fstream::trunc);
file.close();
graph obj;
obj.create();
}
我做错了什么?
答案 0 :(得分:0)
您的问题可能与
有关int x,y;
for(x=1;x<=MAX;x++)
for(y=1;y<=MAX;y++)
gptr[x][y] = 0;
您在数组边界外的访问元素。可能应该是:
int x,y;
for(x=0;x<MAX;x++)
for(y=0;y<MAX;y++)
gptr[x][y] = 0;
您的其他数组/循环也是如此。 C / C ++开始计数0,不像FORTRAN开始计数1(为什么,为什么......)