I have this function that reads a graph from a file formatted this way: numVerticies numEdges on the first line
starting vertex ending vertex edge color for each edge one per line
so it looks like this: 5 6
1 2 C
2 3 W
and so on...
C means crimson, w means white. It works for some graphs, but for others I get a seg fault. Could you please take a look at my code and tell me what's wrong with it? Here's a graph that works fine: https://i.stack.imgur.com/mPzx7.gif
Here's a one that doesnt work: https://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/Undirected_graph.svg/462px-Undirected_graph.svg.png
My code:
//reading the graph the graph from the file and building an adj. matrix for it
int** read_graph(ifstream &fin, int &size) {
fin >> size; //reading the number of verticies
int edges;
fin >> edges; //num of edges
int** graph = new int*[size];
for (int i = 0; i < size; i++) { //creating the matrix
graph[i] = new int[size];
for (int j = 0; j < size; j++) {
if (i == j) graph[i][j] = 0; //0 if row and col match
else graph[i][j] = INT_MAX;
} //inf otherwise
}
for (int i = 0; i < edges; i++) { //reading the edges
int vert1, vert2;
char edge;
fin >> vert1 >> vert2 >> edge;
cout<<"ALIVE "<<vert1<<vert2<<endl;
//if Crimson - 1, else - MAX_EDGE
graph[vert1][vert2] = graph[vert2][vert1] = edge == 'C' ? 1 : MAX_EDGE;
cout<<"ALIVE END"<<endl;
}
return graph;
}
I found the bug. If the naming of my verticies start from 0, no crashing occurs. If they start from one, the final run of the final cycle tries to access an area thats undefined.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.