Was working on an assignment on a Mac machine and the code compiles and I get my expected output. As soon as I go to test it on the Ubuntu machines that the programs are run on for grading I get a Segmentation fault (core dumped) error message. I am really stumped and am looking for some tips for debugging why this occurs on the ubuntu machine (version 12.04) and not the mac machine (mavericks OS).
Edit: Running it through gdb I get the segmentation fault at
in getPath: line 28, if (path[position] == 0 && position == 0) {
My code is as follows:
#include <iostream>
using namespace std;
int minDistance(int distance[], bool shortestPath[]) {
int min = 1000000000;
int indexOfMin;
for (int i = 0; i < 6; i++) {
if (shortestPath[i] == false && distance[i] <= min) {
min = distance[i];
indexOfMin = i;
}
}
return indexOfMin;
}
void getPath(int path[], int position) {
cout << position + 1 << " <- ";
// base case, we hit the end of the path
if (path[position] == 0 && position == 0) {
cout << path[position] + 1 << endl;
}
else if (path[position] == 0)
cout << path[position] + 1 << endl;
else {
getPath(path, path[position]);
}
}
void dijkstraAlgorithm(int weightedGraph[6][6], int sourceVertex) {
int distance[6];
bool shortestPath[6];
int path[6];
for (int i = 0; i < 6; i++) {
distance[i] = 1000000000;
shortestPath[i] = false;
}
distance[sourceVertex] = 0;
for (int j = 0; j < 5; j++) {
int min = minDistance(distance, shortestPath);
shortestPath[min] = true;
for (int k = 0; k < 6; k++) {
if (!shortestPath[k] && weightedGraph[min][k] && distance[min] != 1000000000 && distance[min] + weightedGraph[min][k] < distance[k]) {
distance[k] = weightedGraph[min][k] + distance[min];
path[k] = min;
}
}
}
cout << "Distance Path" << endl;
for (int i = 0; i < 6; i++) {
// dist[i] == 0 a formatting fix for first distance
if (distance[i] == 0) {
cout << distance[i] << ": ";
getPath(path, i);
}
else {
cout << distance[i] << ": ";
getPath(path, i);
}
}
}
int main() {
int weightedGraph[6][6] = {
{0, 10, 0, 30, 100, 0},
{0, 0, 50, 0, 0, 0},
{0, 0, 0, 0, 10, 5},
{0, 0, 20, 0, 0, 15},
{0, 0, 0, 60, 0, 0},
{0, 0, 0, 0, 0, 0}
};
dijkstraAlgorithm(weightedGraph, 0);
return 0;
}
Note: I'm required to use the g++ compiler (version 4.6.4) on the Ubuntu environment