Reputation: 31
I'm new to programming and I tried to implement a graph using adjacency list with c++ programming language.
The upload of the graph data seems to work. But I got a problem when I tried to print the graph: Segmentation fault: 11
. Specifically it happens in the vertex 57. I think that the logic of the program is okay but I don't know where is the error.
The text file : data.txt
And the source code:
//
// main.cpp
// Dijkstra
//
// Created by Ibrahim El Mountasser on 02/12/2018.
// Copyright © 2018 Ibrahim El Mountasser. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
const int SIZE = 201;
struct Node{
int data;
int weight;
struct Node* next;
};
struct LinkedList {
struct Node* head;
};
class Graph {
public: LinkedList list[SIZE];
public:
Graph(std::string fileName) {
std::ifstream infile(fileName);
if(!infile.is_open()) return;
std::string line;
int i = 0;
while ( i < SIZE && getline(infile, line) )
{
std::istringstream str(line);
int u;
int w;
str >> u;
if ( u > SIZE )
{
// Problem.
std::cout<<"u is too large!"<<std::endl;
exit(-1);
}
int v;
char c;
while ( str >> v >> c >> w)
{
if( u < v)
{
createEdge(u, v, w);
std::cout<<"createEdge("<<u<<","<<v<<","<<w<<");"<<std::endl;
}
}
}
}
Node* createNode(int data, int weight){
Node* newNode = new Node;
newNode->data = data;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}
void createEdge(int src, int dist, int weight) {
Node* newNode = createNode(dist, weight);
newNode->next = list[src].head;
list[src].head = newNode;
newNode = createNode(src, weight);
newNode->next = list[dist].head;
list[dist].head = newNode;
}
void printGraph() {
for (int i=0; i<SIZE; i++) {
std::cout<<i;
Node* temp = list[i].head;
while (temp != NULL) {
std::cout<<" -> "<<temp->data<<","<<temp->weight; // <== segfault here
temp = temp->next;
}
std::cout<<std::endl;
}
}
};
int main() {
Graph gr("data.txt");
gr.printGraph(); // <========= segfault when calling this
return 0;
}
Upvotes: 0
Views: 69
Reputation: 80
I think the root problem is this:
newNode->next = list[src].head;
list[src]
is not initialized and just points to random memory.
When you do what @rafix07 mentioned and default initialize it with nullptr, it works.
Upvotes: 1